# Saving a log file if an error occurs

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?

• Have a look at CheckAbort and Catch. – Henrik Schumacher Jan 30 '18 at 0:13
• 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. – Henrik Schumacher Jan 30 '18 at 0:25
• Have you looked at AbortProtect? – m_goldberg Jan 30 '18 at 0:52
• 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. – George Wolfe Jan 30 '18 at 0:56

I think InternalWithLocalSettings is the tool you want to use. The syntax is:

InternalWithLocalSettings[
preliminaryCode, (* can't be aborted *)
body, (* can be aborted *)
postprocessCode (* can't be aborted *)
]


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


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

InternalWithLocalSettings[
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.