Internal`WithLocalSettings
This function (ref#1, ref#2, ref#3) can be used to ensure that some clean-up code will always be executed, even if an abort or other non-local exit occurs within some protected code. To illustrate:
Internal`WithLocalSettings[
Print["opening a file"]
, Print["doing something with the file"]
; Abort[]
; Print["never gets here"]
, Print["closing the file"]
]
(* During evaluation of In[1]:= opening a file
During evaluation of In[1]:= doing something with the file
During evaluation of In[1]:= closing the file
Out[1]= $Aborted
*)
Earlier versions of this function did not handle Catch/Throw properly, but this has been corrected and the function now seems to the most reliable way to protect against the unwinding of the evaluation stack.
Please note that since WL 12.2, WithCleanup is available. It has similar functionality and is documented although currently tagged as "Experimental".
CheckAll
In a similar vein, the CheckAll function (ref) ensures that a function is called whenever a body of code was exited, whether normally or abnormally. Unlike Internal`WithLocalSettings, the handler code completely intercepts the exit. To illustrate:
CheckAll["normal exit", myHandlerFunction]
(* myHandlerFunction["normal exit", Hold[]] *)
CheckAll[Throw[3], myHandlerFunction]
(* myHandlerFunction[$Aborted, Hold[Throw[3]]] *)
The second example shows how the handler function is informed about the exact nature of the exit. It is up to that function to decide whether to re-evaluate the expression that triggered the exit, thus continuing to pass control up the stack.