Previous: , Up: Handling Errors   [Contents][Index]


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, function will be executed after clearing the last copy of the object. Note that if multiple local onCleanup variables are created, the order in which they are called is unspecified. For similar functionality See The unwind_protect Statement.