Contents / Part 3 / Previous chapter / Next chapter / Index
If the computer is unable to deal with a situation such as this:
PRINT 3/0
then it will report the fact to you with an "Error message" and then stop, waiting for your next command
>PRINT 3/0
Division by zero
If you are sitting at the keyboard playing with the machine this is quite acceptable - in fact one of the main virtues of BASIC is that it does try to give you an indication of why it is unable to proceed. However if you are writing a program for someone else to use, and you do not want them to be bothered with error messages then you must take the precautions to deal with every possible erroneous situation that might arise.
The major tool in error-handling is the statement
ON ERROR GOTO 5000
(the 5000 is for example - it could GOTO any line number you like).
Once the computer has encountered an ON ERROR GOTO statement it will no longer report errors and stop - instead it will go to line 5000 (or wherever you have told it to go to). The statement ON ERROR OFF makes the computer handle errors normally again. The computer has an ERROR NUMBER for every error it may encounter and you can use the error number to enable you to know what has gone wrong. The error number is stared in the variable ERR. The error number for an attempt to divide by zero is 18 for example.
10 ON ERROR GOTO 2000
20 PRINT "HELLO"
30 PRINT 3/0
40 PRINT "BYE"
50 END
2000 PRINT ERR
>RUN
HELLO
18
The computer also remembers the line at which it detected the error and this number is stored in the variable ERL.
10 ON ERROR GOTO 2000
20 PRINT "HELLO"
30 PRINT 3/0
40 PRINT "BYE"
50 END
2000 PRINT ERR
2010 PRINT ERL
>RUN
HELLO
18
30
As you will see from the above the computer detected error number 18 in line number 30. Instead of just printing an error number the computer can be made to deal with the problem.
Look at the next program which will generate an error when X gets to zero.
100 X=-5
110 PRINT X, 3/X
120 X=X+1
130 IF X<5 THEN GOTO 110
140 END
>RUN
-5 -0.6
-4 -0.75
-3 -1
-2 -1.5
-1 -3
0
Division by zero at line 110
If we put an error handling routine in we can let the computer deal with the problem itself.
10 ON ERROR GOTO 1000
100 X=-5
110 PRINT X, 3/X
120 X=X+1
130 IF X<5 THEN GOTO 110
140 END
1000 IF ERR=18 THEN PRINT: GOTO 120
1010 REPORT
>RUN
-5 -0.6
-4 -0.75
-3 -1
-2 -1.5
-1 -3
0
1 3
2 1.5
3 1
4 0.75
In the example program above error 18 was dealt with successfully but line 1010 causes it to REPORT other errors in the normal way without trying to deal with them.
It is usually easy, but tedious, to anticipate all the probable errors but careful planning is needed if the error handling is to be effective. In particular you should be aware that when an error occurs you cannot return into a FOR...NEXT or
REPEAT...UNTIL loop or into a procedure or function or subroutine. So long as you are aware of these limitations you can program around them.