Clean Up When Functions Complete
In this section...
“Overview” on page 26-24
“Examples of Cleaning Up a Program Upon Exit” on page 26-25
“Retrieving Information About the Cleanup Routine” on page 26-27
“Using onCleanup Versus try/catch” on page 26-28
“onCleanup in Scripts” on page 26-29
Overview
A good programming practice is to make sure that you leave your program environment
in a clean state that does not interfere with any other program code. For example, you
might want to
- Close any files that you opened for import or export.
- Restore the MATLAB path.
- Lock or unlock memory to prevent or allow erasing MATLAB function or MEX-files.
- Set your working folder back to its default if you have changed it.
- Make sure global and persistent variables are in the correct state.
MATLAB provides the onCleanup function for this purpose. This function, when used
within any program, establishes a cleanup routine for that function. When the function
terminates, whether normally or in the event of an error or Ctrl+C, MATLAB
automatically executes the cleanup routine.
The following statement establishes a cleanup routine cleanupFun for the currently
running program:
cleanupObj = onCleanup(@cleanupFun);
When your program exits, MATLAB finds any instances of the onCleanup class and
executes the associated function handles. The process of generating and activating
function cleanup involves the following steps:
(^1) Write one or more cleanup routines for the program under development. Assume for
now that it takes only one such routine.
26 Error Handling