Take a look at onCleanup
, which is intended for exactly this purpose.
onCleanup
creates an object that, when it goes out of scope (and therefore gets deleted), executes some code. So, for example,
c1 = onCleanup(@() disp('goodbye'))
creates an object c1
. When c1
goes out of scope, it is deleted, and goodbye
is displayed. Similarly
c2 = onCleanup(@() fclose(fid))
creates an object that, when deleted, closes the file with ID fid
.
You'll need to make a change to your coding style to take advantage of onCleanup
- specifically, you'll need to implement things as functions rather than scripts. Scripts use the base workspace, so when the finish, any cleanup objects you've created remain in the base workspace without going out of scope and being deleted, so their code never executes.
By contrast, functions have their own workspace, which is cleared when they finish, automatically deleting any cleanup objects. Importantly for your question, this workspace is cleared not only when the function finishes normally, but also if it finishes with an error, and even if it finishes with CtrlC.
It's usually simple to modify a script to a function: if the script is called mytest.m
, just put function mytest
at the top of the script. There are situations where this won't work (e.g. if your script depends on other variables being available in the base workspace), but those are situations that it's not a good idea to be in anyway.
As an example, run the following program:
function mytest
c = onCleanup(@() disp('goodbye'));
for i = 1:1000000
disp(i)
end
During execution, hit CtrlC. You should see that goodbye
is displayed after the last number.