# In a Function, how to Ensure Code Runs Prior to an Abort [duplicate]

Is there a way to set aside some code in a function that will be triggered to run if the evaluation of the function is aborted by a user? Specifically, I have a function that has to open a log file to write to, but the algorithm in the function in many cases doesn't finish so it has to be aborted:

f[]:= Module[{},
logstream = OpenWrite["logfile.txt"];
(*  algorithm that often doesn't finish  *)
Close[logstream];
];


Is there some way to ensure within the function that the Close[logstream] gets run even if the function gets manually aborted in the loop? (Or is there some other mechanism to achieve the same thing?) I've come across AbortProtect[] which seems like it should be useful here, but I don't think it's applicable in this situation.

• Have a look here and here. In fact, your question is probably a dupe of the latter. – Leonid Shifrin Jun 12 '14 at 18:51