Like many high level languages Forth does not have an explicit GOTO. This means that it is often necessary to create proprietary solutions to errors that occur in running embedded code. To help with this the CATCH and THROW words have been added to the AVR Forth to assist with error conditions.
The CATCH word takes a CFA from the data stack and executes it after first placing its position and the current stack depths onto the return stack. The word HANDLER records the position of this stack frame for later use by THROW and its previous value is also saved to allow nested CATCH-THROW structures.
Use: ' <word> CATCH ERROR !
CATCH allows a value to be returned to show the error condition. If no errors are encountered <word> finishes normally and returns to after CATCH.
When an error is encountered in the word run by CATCH a non-zero value is placed on the data stack and THROW executed. THROW takes the value in HANDLER and restores the stacks to where they were when CATCH was executed except for the addition of the non-zero value given to THROW.
Use: ?DUP IF THROW THEN
HANDLER is a USER variable in multi-tasking systems and so the error recovery may be used within each task.