6 Branching and Subroutines
* Parameters cannot be passed.
* Parameter can not be passed
The ON ERROR statement declares what should happen if an error occurs. It need be executed only once in each program segment to establish the ON ERROR condition. Execution of another ON ERROR statement cancels the previous one.
When a run-time error occurs and the ON ERROR condition has been established, execution is transferred to the specified line. Then the ERRN and ERRL functions discussed next can be tested, and either error recovery procedures or DISP ERRM$ can be executed. The error is ignored if the statement referenced by a GOSUB is a RETURN statement; execution continues with the line after the one in which the error occurred.
If the error-recovery routine itself contains an error, the program may possibly run in an endless loop. This can be stopped by pressing BREAK or CTRL Y.
If the ON ERROR statement specifies a GOSUB or CALL, computer priority is set at the highest level until the routine has been completed. The routine can be interrupted only by an ON END or another ON ERROR interrupt. (ON END is described in page 195 .) A routine accessed with GOTO can be interrupted because system priority is not changed.
The following string and numeric functions return information related to the last error trapped with ON ERROR:
OFF ERROR
The following program sequence shows how ON ERROR can be used to detect errors and display an appropriate message:
10 OPTION BASE 1 20 DIM A(50) 30 ON ERROR GOTO Recovery1 40 Print: INPUT "Enter file name:",F$ 50 ASSIGN #1 TO "F$" 60 FOR R=1 TO 50 70 PRINT #1,R;A(R) 80 NEXT R 90 PRINT "DATA PRINTED ON FILE." 100 GOTO Read 110 Recovery1: ! Check for errors 53 and 56. 120 IF ERRN=53 THEN E53 130 IF ERRN=56 THEN E56 140 GOTO Exit 150 E53: PRINT PAGE;"IMPROPER FILE NAME - PRESS <RETURN> TO CONTINUE." 160 INPUT 170 GOTO Print 180 E56: PRINT PAGE;"FILE NAME IS UNDEFINED - PRESS <RETURN> TO CONTINUE." 190 INPUT 200 GOTO Print 210 Exit: PRINT "ERRM$" ! Print error number and line. 220 STOP 230 Read: ! Continue program. . . .Line 30 activates an ON ERROR condition which will branch the program to the Recovery1 routine if an error occurs. The Print routine prints data elements of array A into sequential records of a data file. If any error occurs here, the program would branch to Recovery1, rather than print DATA PRINTED ON FILE and continue at the Read routine.
The Read routine begins by deactivating the first ON ERROR routine and activating a new one.
The Recovery1 routine checks for errors 53 and 56. The routine responds to errors 53 and 56 with a displayed message and then returns to the Print routine where the operator can correct the error.
Notice that if any error but 53 or 56 occurs while Recovery1 is active, the Exit routine first displays ERRM$, containing the error number and line, and then stops.