Node:Exceptions Tutorial, Next:, Previous:Execution Tokens Tutorial, Up:Tutorial



Exceptions

throw ( n -- ) causes an exception unless n is zero.

100 throw .s
0 throw .s

catch ( ... xt -- ... n ) behaves similar to execute, but 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 catch:

.s
3 0 ' / catch .s
3 2 ' / catch .s
Assignment:
Try the same with execute instead of catch.

Throw always jumps to the dynamically next enclosing catch, even if it has to leave several call levels to achieve this:

: 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 like this:

: ...
   save-x
   ['] word-changing-x catch ( ... n )
   restore-x
   ( ... n ) throw ;

Gforth provides an alternative syntax in addition to catch: try ... recover ... endtry. If the code between try and recover has an exception, the stack depths are restored, the exception number is pushed on the stack, and the code between recover and endtry is performed. E.g., the definition for catch is

: 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 recover and endtry to balance the stack.

Reference: Exception Handling.