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.

© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v6.3.0/Recovering-From-Errors.html