| www.delorie.com/gnu/docs/gforth/gforth_46.html | search |
![]() Buy GNU books! | |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
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 |
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
end-try
restore-x
throw ;
|
As you can see, the recover part is optional.
Reference: 5.8.6 Exception Handling.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
| webmaster donations bookstore | delorie software privacy |
| Copyright © 2003 by The Free Software Foundation | Updated Jun 2003 |