Exceptions: Difference between revisions

(→‎[[Standard ML]]: Added Forth)
Line 141:
Forth's exception mechanism is, like most things in Forth, very simple but powerful.
CATCH captures the data and return stack pointers, then exectutes an execution token.
THROW conditionally throws a value up to the most recent CATCH, restoring the stack pointers.
 
===Throw Exceptions===
: f ( -- ) 1 throw ." f " ; \ will throw a "1"
: g ( -- ) 0 throw ." g " ; \ does not throw
 
===Catch Exceptions===
: report ( n -- ) ?dup if ." caught " . else ." no throw" then ;
: test ( -- )
['] f catch report
['] g catch report ;
test example. (Output shown in bold)
cr test
'''caught 1 g no throw ok'''
 
Note that CATCH only restores the stack pointers, not the stack values, so any values that were changed during the execution of the token will have undefined values. In practice, this means writing code to clean up the stack, like this:
10 ['] myfun catch if drop then
 
==[[Standard ML]]==
Anonymous user