Node:Exceptions Tutorial, Next:Defining Words Tutorial, Previous:Execution Tokens Tutorial, Up:Tutorial
throw ( n -- ) causes an exception unless n is zero.
100 throw .s 0 throw .s
catch ( ... xt -- ... n ) behaves similar to
it catches exceptions and pushes the number of the exception on the
stack (or 0, if the xt executed without exception). If there was an
exception, the stacks have the same depth as when entering
.s 3 0 ' / catch .s 3 2 ' / catch .s
Throw always jumps to the dynamically next enclosing
catch, even if it has to leave several call levels to achieve
: foo 100 throw ; : foo1 foo ." after foo" ; : bar ['] foo1 catch ; bar .
It is often important to restore a value upon leaving a definition, even
if the definition is left through an exception. You can ensure this
: ... save-x ['] word-changing-x catch ( ... n ) restore-x ( ... n ) throw ;
Gforth provides an alternative syntax in addition to
try ... recover ... endtry. If the code between
recover has an exception, the stack depths are restored, the
exception number is pushed on the stack, and the code between
endtry is performed. E.g., the definition for
: catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception try execute 0 recover nip endtry ;
The equivalent to the restoration code above is
: ... save-x try word-changing-x 0 recover endtry restore-x throw ;
This works if
word-changing-x does not change the stack depth,
otherwise you should add some code between
endtry to balance the stack.
Reference: Exception Handling.