(^2) Create a function handle for the cleanup routine.
(^3) At some point, generally early in your program code, insert a call to the oncleanup
function, passing the function handle.
(^4) When the program is run, the call to onCleanup constructs a cleanup object that
contains a handle to the cleanup routine created in step 1.
(^5) When the program ends, MATLAB implicitly clears all objects that are local variables.
This invokes the destructor method for each local object in your program, including
the cleanup object constructed in step 4.
(^6) The destructor method for this object invokes this routine if it exists. This perform
the tasks needed to restore your programming environment.
You can declare any number of cleanup routines for a program file. Each call to
onCleanup establishes a separate cleanup routine for each cleanup object returned.
If, for some reason, the object returned by onCleanup persists beyond the life of your
program, then the cleanup routine associated with that object is not run when your
function terminates. Instead, it will run whenever the object is destroyed (e.g., by clearing
the object variable).
Your cleanup routine should never rely on variables that are defined outside of that
routine. For example, the nested function shown here on the left executes with no error,
whereas the very similar one on the right fails with the error, Undefined function or
variable 'k'. This results from the cleanup routine's reliance on variable k which is
defined outside of the nested cleanup routine:
function testCleanup function testCleanup
k = 3; k = 3;
myFun obj = onCleanup(@myFun);
function myFun function myFun
fprintf('k is %d\n', k) fprintf('k is %d\n', k)
end end
end end
Examples of Cleaning Up a Program Upon Exit
Example 1 — Close Open Files on Exit
MATLAB closes the file with identifier fid when function openFileSafely terminates:
function openFileSafely(fileName)
fid = fopen(fileName, 'r');
Clean Up When Functions Complete
やまだぃちぅ
(やまだぃちぅ)
#1