Knowledge Base

ON Event GOSUB, ON ERROR GOTO Labels Must Be in Main Program

Article ID: 20541

Article Last Modified on 11/21/2006


APPLIES TO


This article was previously published under Q20541

SUMMARY

This article describes how to perform event and error trapping in subprograms. This information applies to Microsoft QuickBASIC Versions 1.00, 1.00a, 1.00b, Microsoft BASIC Compiler Version 1.00, and Microsoft BASIC Interpreter Versions 2.00, 2.10, and 3.00 for the Apple Macintosh.

You can use the "ON ERROR" and "ON event" trapping statements in subprograms; however, the error-handling subroutine label given in the GOTO or GOSUB statement must be located outside the subprogram, as follows:
    CALL Mytest
    END               ' Run the subprogram Mytest then stop.
    SUB Mytest STATIC
      ON ERROR GOTO Errorhandler    ' Turn on error trapping.
      ERROR 200                     ' Simulates an error.
      PRINT "This was printed after the error"
    END SUB
    ' The error handler must be outside the SUBprogram block:
    Errorhandler:
       PRINT "Error trapped=";ERR
       RESUME NEXT   ' Resumes on next line after error occurred.
				
Error and event-handler code must be outside of subprograms because error and event handlers are global across the whole program. When trapping errors that occur in a subprogram, you cannot use the RESUME <line> statement, you may only use RESUME or RESUME NEXT.

Note also that labels and line numbers are also global across the whole program. Labels or line numbers used in a subprogram cannot be used in the main program.

Additional query words: BasicCom MQuickB

Keywords: KB20541