Run the modified function to see the output of the functions command and the contents
of one of the workspace cells:
showImageOutsidePath('greens.jpg')
Opening the figure greens.jpg
Displaying information from the function handle:
fun =
function: '@()restore_env(fig1,imgpath)'
type: 'anonymous'
file: 'c:\work\g6.m'
workspace: {2x1 cell}
wsp =
imageFile: 'greens.jpg'
fig1: 1
imgpath: [1x3957 char]
cleanupObj: [1x1 onCleanup]
rgb: [300x500x3 uint8]
task: @()restore_env(fig1,imgpath)
Closing the figure
Restoring the path
Using onCleanup Versus try/catch
Another way to run a cleanup routine when a function terminates unexpectedly is to use a
try, catch statement. There are limitations to using this technique however. If the user
ends the program by typing Ctrl+C, MATLAB immediately exits the try block, and the
cleanup routine never executes. The cleanup routine also does not run when you exit the
function normally.
The following program cleans up if an error occurs, but not in response to Ctrl+C:
function cleanupByCatch
try
pause(10);
catch
disp(' Collecting information about the error')
disp(' Executing cleanup tasks')
end
Unlike the try/catch statement, the onCleanup function responds not only to a normal
exit from your program and any error that might be thrown, but also to Ctrl+C. This next
example replaces the try/catch with onCleanup:
26 Error Handling