Visual Basic Concepts
Turning Off Error Handling
If an error trap has been enabled in a procedure, it is automatically disabled when the procedure finishes executing. However, you may want to turn off an error trap in a procedure while the code in that procedure is still executing. To turn off an enabled error trap, use the On Error GoTo 0 statement. Once Visual Basic executes this statement, errors are detected but not trapped within the procedure. You can use On Error GoTo 0 to turn off error handling anywhere in a procedure — even within an error-handling routine itself.
For example, try single stepping, using Step Into, through a procedure such as this:
Sub ErrDemoSub () On Error GoTo SubHandler ' Error trapping is ' enabled. ' Errors need to be caught and corrected here. ' The Kill function is used to delete a file. Kill "Oldfile.xyz" On Error GoTo 0 ' Error trapping is turned off ' here. Kill "Oldfile.xyz" On Error GoTo SubHandler ' Error trapping is ' enabled again. Kill "Oldfile.xyz" Exit Sub SubHandler: ' Error-handling routine goes here. MsgBox "Caught error." Resume Next End Sub
*For More Information* To learn how to use the Step Into feature, see "Running Selected Portions of Your Application" later in this chapter.
Debugging Code with Error Handlers
When you are debugging code, you may find it confusing to analyze its behavior when it generates errors that are trapped by an error handler. You could comment out the On Error line in each module in the project, but this is also cumbersome.
Instead, while debugging, you could turn off error handlers so that every time there's an error, you enter break mode.
To disable error handlers while debugging
From the Code window context menu (available by right-clicking on the Code window), choose Toggle.
Select the Break on All Errors option.
With this option selected, when an error occurs anywhere in the project, you will enter break mode and the Code window will display the code where the error occurred.
If this option is not selected, an error may or may not cause an error message to be displayed, depending on where the error occurred. For example, it may have been raised by an external object referenced by your application. If it does display a message, it may be meaningless, depending on where the error originated.