Is there a way to know when an MATLAB exits? I wanted to do some work, for example, release some resource, print some logs... I could add some code at some class's destructors. But since we cannot determine the order that MATLAB calls destructors, I am not sure which one is the last one so I can release the resource.
Can we register any callback to the MATLAB exit event if there exists such an event...?
There is no exit event I know of that's thrown when exiting from a function or MATLAB itself. However, there are two things you can do to handle final cleanup:
Use onCleanUp objects: When exiting from a function, variables in the local workspace are destroyed (and exiting from MATLAB itself will destroy objects in the base workspace). When working with resources (files, etc.), good practice is to create an onCleanUp
object to handle those resources in an exception-safe manner. This is discussed in more detail in the documentation and this question: How do you handle resources in MATLAB in an exception safe manner? (like “try … finally”)
Create a finish.m
file: When quitting MATLAB, it will look on the search path for a file named finish.m
and run that code before terminating.
You can place any cleanup actions in the finish.m file.
Similar to startup.m, MATLAB executes this file (when found on the MATLAB search path) just prior to program termination.
Also worth looking into is onCleanup. This simple class creates an object that, when destroyed, runs the function registered during object creation. This is extremely useful when dealing with files for example:
fid = fopen(filename, 'r');
OC = onCleanup(@() any(fopen('all')==fid) && fclose(fid));
% ...file reading and processing here
% ERROR HAPPENS HERE!
% ... more processing here
fclose(fid);
meaning, the file handle fid
is still closed, even though the normal fclose(fid)
was not reached. This is because the object OC
was cleared implicitly by MATLAB after the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With