| Contents | Index |
cleanupObj = onCleanup(@cleanupFun)
cleanupObj = onCleanup(@cleanupFun) when called in a function F, specifies any cleanup tasks that are to be performed when F terminates. An example of a cleanup task might be to close any files that have been opened by F. You specify one or more of these tasks in a separate function, shown here as cleanupFun, and MATLAB automatically executes this function at the time function F terminates.
onCleanup returns a class object cleanupObj that has two important roles:
cleanupObj stores, and later provides access to, the function cleanup routine cleanupFun.
The clearing of cleanupObj at the time function F terminates invokes this cleanup routine.
All objects that are local variables in a function are implicitly cleared at the termination of that function, whether by normal completion or by a forced exit such as an error or Ctrl+C. When function F terminates, MATLAB clears the cleanupObj object by calling its object destructor method. The destructor executes the cleanup routine at that time. The cleanup routine then performs the necessary cleanup tasks for function F.
See Cleaning Up When the Function Completes for more information on how to use this function.
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.
Use onCleanup to close a file in the first example, and to restore the current folder in the second:
function fileOpenSafely(fileName) fid = fopen(fileName, 'w'); c = onCleanup(@()fclose(fid)); functionThatMayError(fid); end % c executes fclose(fid) here
MATLAB closes fid whether functionThatMayError returns an error or not.
function changeFolderSafely(fileName) currentFolder = pwd; c = onCleanup(@()cd(currentFolder)); functionThatMayError; end % c executes cd(currentFolder) here
The current folder is preserved whether functionThatMayError returns an error or not.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |