onCleanup

Creates an object that runs a function when it is cleared or goes out of scope.

Category: Programming > Functions

Syntax

c = onCleanup(task)

Returns a cleanup object that calls the function handle task with no arguments when c is destroyed.

Description

A local variable is destroyed when its function returns, whether normally or through an error. Holding an onCleanup object in such a variable therefore guarantees that the task runs on every exit path. This is the standard way to close files, restore settings or delete temporary data without writing the cleanup in several places.

The task also runs if the variable is overwritten or removed with clear.

Input arguments

task
Function handle taking no inputs, for example @() fclose(fid).

Output arguments

c
An onCleanup object. Keep it in a variable; discarding it runs the task at once.

Example

Cleanup on function exit and on clear

function work()
    c = onCleanup(@() fprintf('leaving\n'));
    fprintf('working\n');
end
work();
x = onCleanup(@() disp('cleared'));
clear x
disp('done')
Output
working
leaving
cleared
done

See also

clear fclose try, catch delete