Exceptions CATCH-THROW

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 PIC18F Forth to assist with error conditions.

CATCH

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 PIC 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 with a zero value that will be stored in the variable ERROR. We could test the value and if non-zero THROW again to futher up the code or perform some corrective measure.

THROW

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.

Note: The lower 11 bits of the Forth Return Stack pointer is saved along with the 5 bits of the PIC stack pointer. This means that for CATCH and THROW to work the task areas must be in the first 2k of file memory.