Structured Error Handling

Ever wanted to run a subroutine easily trap any error in the logic? A new ON ERR option allows for easy trapping and processing of errors within various blocks of logic within your code.

The directives GOSUB, WHILE, FOR, REPEAT and SELECT now support an enhanced ON ERR option that allows you to specify what logic is to be executed should an error occur within their respective logic block.

Example:

GOSUB LOAD_CLIENT ON ERR PRINT “Unable to load client”

Including an ON ERR clause following the label/statement number in a GOSUB tells the system that should an un-trapped error occur when processing the GOSUB logic, the system is to execute the remainder of the line following ON ERR.

By default, the complete line following the ON ERR will be processed however you may also include curly brackets to define the logic to be executed as in:

WHILE 1 ON ERR {BREAK}; READ (1) R$; PRINT R$; WEND

In this case if an error occur during the WHILE loop (in this example an end of file) the system will transfer control to the BREAK directive.

Note that in the above example, the system actually transfers control to the ON ERR clause but does not actually exit the WHILE loop. Should the ON ERR logic not exit the loop or cause the loop to terminate the loop will continue to execute. For Example:

N = 4
WHILE N>-3 ON ERR PRINT “Cannot process “,N
--N
X = 10 / N
PRINT “10 / “,N,”=”,X
WEND

This code will generate a divide error when N equals zero at which point the ON ERR logic will be executed.

The ON ERR clause is automatically cascaded to lower levels thus an un-trapped error at a lower level will cause the system to exit the lower levels and return control to the upper level to handle the error. For example. if we modify the prior example:

N = 4
WHILE N>-3 ON ERR PRINT “Cannot process “,N
--N
GOSUB CHECK_N
WEND
….

CHECK_N:

X = 10 / N
PRINT “10 / “,N,”=”,X
RETURN

The actual divide error will occur in the lower level GOSUB however the existence of the ON ERR clause will result in the system automatically exiting the GOSUB and returning control to the outer WHILE loop.

For all but the GOSUB, the ON ERR logic will be executed while functionally still within the loop structure. The system just executes the ON ERR logic and continues processing the loop unless the ON ERR logic itself caused the loop to terminate (such as by issuing a BREAK).

In the case of the GOSUB, the subroutine exits first and then the ON ERR logic is executed.

Special processing is allotted to “ON ERR ESCAPE”. If the first directive in the ON ERR clause is ESCAPE, the system will simply issue an internal ESCAPE when an un-trapped error occurs.