OnError

=On Error Goto= toc Run BASIC offers simple error handling with the **On Error Goto [branchLabel]** statement. The syntax is as follows:

Syntax
ON ERROR GOTO [errorHandler] //- Specify an error handler label. The handler must be in the outermost scope.// //No support for RESUME.//

The error handler must be a branch label. It cannot be a SUB.

Error Numbers
Once an error is encountered, the error number is contained in the special Run BASIC variable, **Err**. It is case sensitive.

Error Descriptions
Once an error is encountered, the error description is contained in the special Run BASIC variable, **Err$**. It is case sensitive.

Simple Demonstration
The following small program introduces an error by attempting to divide by zero. The error handler prints out the error number and error name, then waits.

code format="vbnet" on error goto [oops]

'introduce an error: x = 10/0 wait

[oops] print "Error is ";Err$ print "Error number is ";Err wait code

Conditional Error Handling
You may use the information in **Err** and **Err$** to control program flow. The following variation of the program above checks for a "divide by zero" error, changes the value of the divisor (x) when the error is encountered, and directs program flow. If a different error is found, the program is stopped and the error is reported. More extensive error handling would be used in a real program, of course.

code format="vbnet" on error goto [oops]

'introduce an error: x = 0

[fixMe] y = 23/x print "23/x is ";y wait

[oops] 'if error is *divide by zero,* 'change value of x and try again. if Err = 11 then x = 1 goto [fixMe] end if

print "Cannot continue. Error is ";Err$ wait

code