Clean Up When Functions Complete

Contents

What to clean up

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

onCleanup

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.

Opening a file for write without cleaning up

First attempt to write the file incorrectly

filename = 'test.txt';
data = { 'This is a cell and cannot be written' };
try
    myUnsafeFileWriter( filename, data )
catch err
    err.message
end
ans =

Function is not defined for 'cell' inputs.

Observe that the file handle is still open and we cannot delete it

fopen('all')
delete( filename )
ans =

     []

Perform brute force cleanup

These type of functions are the equivalent of clear all, close all

fclose( 'all' )
ans =

     0

Opening a file for write with cleaning up

Write the file incorrectly

try
    mySafeFileWriter( filename, data )
catch err
    err.message
end
ans =

Function is not defined for 'cell' inputs.

Observe that the file handle is no longer open and we can delete it

fopen('all')
delete( filename )
ans =

     []