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.