W3cubDocs

/Octave

10.8 The unwind_protect Statement

Octave supports a limited form of exception handling modeled after the unwind-protect form of Lisp.

The general form of an unwind_protect block looks like this:

unwind_protect
  body
unwind_protect_cleanup
  cleanup
end_unwind_protect

where body and cleanup are both optional and may contain any Octave expressions or commands. The statements in cleanup are guaranteed to be executed regardless of how control exits body.

This is useful to protect temporary changes to global variables from possible errors. For example, the following code will always restore the original value of the global variable frobnosticate even if an error occurs in the first part of the unwind_protect block.

save_frobnosticate = frobnosticate;
unwind_protect
  frobnosticate = true;
  …
unwind_protect_cleanup
  frobnosticate = save_frobnosticate;
end_unwind_protect

Without unwind_protect, the value of frobnosticate would not be restored if an error occurs while evaluating the first part of the unwind_protect block because evaluation would stop at the point of the error and the statement to restore the value would not be executed.

In addition to unwind_protect, Octave supports another form of exception handling, the try block.

© 1996–2018 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/interpreter/The-unwind_005fprotect-Statement.html