ON ERROR statement

Purpose

Specify an error handling routine; enable or disable error trapping.

Syntax

ON ERROR GOTO {label | line_number}

ON ERROR RESUME NEXT

ON ERROR GOTO 0

Remarks

label or line_number identifies the first line of the error trapping routine.  Once error handling has been turned on with this statement, all run-time errors result in a jump to your error handling code.  You must always use the RESUME statement to continue execution once the error has been handled.

To disable error trapping, use ON ERROR GOTO 0 or ON ERROR RESUME NEXT.  You can use this technique if an error occurs for which you have not defined a recovery path; you can also choose to display the contents of ERR or ERRCLEAR at this time.

The default for error trapping is disabled.  If an error occurs while error trapping is disabled, the error code is placed into the ERR system variable, and execution continues.  Errors can still be trapped by checking the value of the ERR or ERRCLEAR variable with IF ERR THEN or SELECT CASE ERR statements.

Error trapping is local to each Sub, Function, Method, and Property.  PowerBASIC does not support global error trapping.

Numeric errors such as Divide-by-zero, Overflow and Underflow are not trapped.  Array out-of-bounds and null-pointer trapping are only enabled if #DEBUG ERROR ON is used.

If you're running a program with error trapping turned off, a run-time error may cause a General Protection Fault (GPF).  A GPF cannot be trapped with ON ERROR.

It is not possible to branch to an error handler from within an expression. The compiler tests for an error only after the statement is completed. This means that a statement such as:

...

ON ERROR GOTO ErrorHandlerLabel

IF GETATTR(sFile) THEN
 ...
END IF

will generate an Error 53 when sFile does not exist, but will not branch to the ErrorHandlerLabel. This is because the GETATTR(sFile) is an expression in the IF/ END IF block. You could do a

...

ON ERROR GOTO ErrorHandlerLabel

a& = GETATTR(sFile)

IF a& THEN
...
END IF

which will branch to the ErrorHandlerLabel if sFile does not exists. You could also check the value of the ERR variable or use a TRY/ END TRY block to see if an error occurred when checking for errors that occur during an expression.

See also

#DEBUG DISPLAY, #DEBUG ERROR, ERR, ERRCLEAR, ERROR, Error OverviewERROR$, Errors and Error TrappingRESUME, Run-time Errors