12.1.3 Recovering From Errors

Octave provides several ways of recovering from errors. There are try/catch blocks, unwind_protect/unwind_protect_cleanup blocks, and finally the onCleanup command.

The onCleanup command associates an ordinary Octave variable (the trigger) with an arbitrary function (the action). Whenever the Octave variable ceases to exist—whether due to a function return, an error, or simply because the variable has been removed with clear—then the assigned function is executed.

The function can do anything necessary for cleanup such as closing open file handles, printing an error message, or restoring global variables to their initial values. The last example is a very convenient idiom for Octave code. For example:

function rand42
  old_state = rand ("state");
  restore_state = onCleanup (@() rand ("state", old_state));
  rand ("state", 42);
  ...
endfunction  # rand generator state restored by onCleanup
 
: obj = onCleanup (function)

Create a special object that executes a given function upon destruction.

If the object is copied to multiple variables (or cell or struct array elements) or returned from a function, then function will be executed only after the last copy of the object is cleared.

The input function is a handle to a function. The handle may point to an anonymous function in order to directly place commands in the onCleanup call.

Programming Note: If multiple local onCleanup variables are created, the order in which they are called is unspecified. For similar functionality See The unwind_protect Statement.

Example

octave:1> trigger = onCleanup (@() disp ('onCleanup was executed'));
octave:2> clear trigger
onCleanup was executed
octave:3