octave-maintainers
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: thoughts about unwind_protect


From: David Bateman
Subject: Re: thoughts about unwind_protect
Date: Mon, 04 Jan 2010 22:31:55 +0100
User-agent: Mozilla-Thunderbird 2.0.0.22 (X11/20090706)

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.


--
David Bateman                                address@hidden
35 rue Gambetta                              +33 1 46 04 02 18 (Home)
92100 Boulogne-Billancourt FRANCE            +33 6 72 01 06 33 (Mob)



reply via email to

[Prev in Thread] Current Thread [Next in Thread]