Robert T. Short wrote:
I have a general question about unwind_protect.
Would someone take the time to explain the advantages of
unwind_protect over try/catch?
From the FAQ
Octave has a lisp like unwind_protect block that allows blocks of
code that terminate in an error to ensure that the variables that
are touched are restored. You can do something similar with
@code{try}/@code{catch} combined with @samp{rethrow (lasterror ())} in
@sc{Matlab}, however rethrow and lasterror are only available in
Octave 2.9.10 and later.
Note that using @code{try}/@code{catch} combined with @samp{rethrow
(lasterror ())} can not guarantee that global variables will be
correctly reset, as it won't catch user interrupts with Ctrl-C. For
example
@example
@group
global a
a = 1;
try
_a = a;
a = 2
while true
end
catch
fprintf ('caught interrupt\n');
a = _a;
rethrow (lasterror());
end
@end group
@end example
@noindent
compared to
@example
@group
global a
a = 1;
unwind_protect
_a = a;
a = 2
while true
end
unwind_protect_cleanup
fprintf ('caught interrupt\n');
a = _a;
end
@end group
@end example
Typing Ctrl-C in the first case returns the user directly to the
prompt, and the variable "a" is not reset to the saved value. In the
second case the variable "a" is reset correctly. Therefore @sc{Matlab}
gives no save way of temporarily changing global variables.