3
$\begingroup$

I am running a program that adds a message to a list after each completed cycle (about 5k cycles). Upon completion, the program saves the list to disk so I can review it.

However, if the program aborts, I lose the list. Can I write an error handler that, with its dying breath, will save that list?

$\endgroup$
  • 1
    $\begingroup$ Have a look at CheckAbort and Catch. $\endgroup$ – Henrik Schumacher Jan 30 '18 at 0:13
  • $\begingroup$ Still, if the kernel crashes, that might be of few use. A safer way would be to write the messages to file every now and then. See, e.g. OpenAppend and friends. $\endgroup$ – Henrik Schumacher Jan 30 '18 at 0:25
  • 1
    $\begingroup$ Have you looked at AbortProtect? $\endgroup$ – m_goldberg Jan 30 '18 at 0:52
  • $\begingroup$ I just discovered it. It seems that wrapping everything in 'AbortProtect' and including 'TimeConstrained' would handle a lot. I actually don't see many aborts, the program encounters an error of some in a function that never finishes evaluating. $\endgroup$ – George Wolfe Jan 30 '18 at 0:56
7
$\begingroup$

I think Internal`WithLocalSettings is the tool you want to use. The syntax is:

Internal`WithLocalSettings[
    preliminaryCode, (* can't be aborted *)
    body, (* can be aborted *)
    postprocessCode (* can't be aborted *)
]

Suppose your code looks like:

code[] := (a=1; b=2; Pause[Infinity]; c=3)

and you're interested in the values of a, b and c. Then:

Internal`WithLocalSettings[
    Null,
    code[],
    Print[{a, b, c}]
]

{1,2,c}

$Aborted[]

where I used Evaluation | Abort Evaluation (actually, the shortcut Cmd + .). Note that code[] got aborted, yet the Print statement still occurred, where I use Print as a substitute for some sort of save file utility.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.