Error Handling

The ON ERROR command directs BBC BASIC (Z80) to execute the statement(s) following ON ERROR when a trappable error occurs:


If an error was detected in a program after this line had been encountered, the message 'Oh No!' would be printed and the program terminated. If, as in this example, the ON ERROR line contains the END statement or transfers control elsewhere (e.g. using GOTO) then the position of the line within the program is unimportant so long as it is encountered before the error occurs. If there is no transfer of control, execution following the error continues as usual on the succeeding line, so in this case the position of the ON ERROR line can matter.

As explained in the Flow Control sub-section, every time BBC BASIC (Z80) encounters a FOR, REPEAT, GOSUB, FN or PROC statement it 'pushes' the return address on to a 'stack' and every time it encounters a NEXT, UNTIL, RETURN statement or the end of a function or procedure it 'pops' the latest return address of the stack and goes back there. The program stack is where BBC BASIC (Z80) records where it is within the structure of your program.

When an error is detected by BBC BASIC (Z80), the stack is cleared. Thus, you cannot just take any necessary action depending on the error and return to where you were because BBC BASIC (Z80) no longer knows where you were.

If an error occurs within a procedure or function, the value of any private variables will be the last value they were set to within the procedure or function which gave rise to the error.