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.  When the error handler begins execution, additional error trapping is temporarily suspended.  When your error handling is complete, you must use the RESUME statement (any form) to continue execution.  RESUME reactivates the temporary suspension of error trapping.

You must use additional care when you trap an error within a GOSUB block of code, because a RETURN address has been saved on the system stack.  If you use a form of RESUME which re-enters the GOSUB block, a RETURN will still be executed later, and the stack will be balanced.  However, if RESUME <Label> or RESUME FLUSH redirects execution elsewhere, you must use RETURN FLUSH to remove the return address from the stack.

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
  ' Do something
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
  ' Do something
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