onCleanup - Cleanup tasks at function completion

Syntax

C = onCleanup(S)

Description

C = onCleanup(S) when called in function F, specifies any cleanup tasks that need to be performed when F completes. S is a handle to a function that performs necessary cleanup work when F exits. (For example, closing files that have been opened by F). S is called whether F exits normally or because of an error.

onCleanup is a MATLAB class and C = onCleanup(S) constructs an instance C of that class. Whenever an object of this class is explicitly or implicitly cleared from the workspace, it runs the cleanup function, S. Objects that are local variables in a function are implicitly cleared at the termination of that function.

Examples

Use onCleanup to close a file in the first example, and to restore the current directory 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 changeDirectorySafely(fileName)
   currentDir = pwd;
   c = onCleanup(@()cd(currentDir));

   functionThatMayError;
end   % c executes cd(currentDir) here

The current directory is preserved whether functionThatMayError returns an error or not.

See Also

clear, clearvars

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS