2
$\begingroup$

This question already has an answer here:

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.

$\endgroup$

marked as duplicate by Leonid Shifrin, Szabolcs, Öskå, Sjoerd C. de Vries, m_goldberg Jun 12 '14 at 20:36

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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