Trapping Runtime Errors
The first step in dealing with runtime errors is to set a "trap" to catch the error. You do this by including an On Error statement in your macro. When a runtime error occurs, the On Error statement transfers control to an error-handling routine. (Refer to the On Error statement topic in the Visual Basic Help for more information.)
To trap errors correctly, you must set your error trap above the point in the procedure where errors are likely to occur. In general, this means that your error trap should be placed near the top of the procedure. Further, to avoid having the error-handling routine execute even when no error occurs, you should include an Exit Sub or Exit Function statement just before the error-handling routine's label.
Each of the following examples show the general structure of a procedure that includes an error trap and error-handling routine.
- In this example, the On Error statement specifies the name of an error handler (called MyHandler) to which control is transferred when a runtime error occurs. After the error is handled, the macro terminates:
Sub SampleWithoutResume () On Error GoTo MyHandler
'Program code goes here. To avoid invoking 'the error handling routine after this 'section is executed, include the following 'line just above the error-handler. Exit Sub
MyHandler: 'Error is handled and the macro terminates 'gracefully. Exit Sub
End Sub
- This example, control resumes at the line following the statement that caused the runtime error:
Sub SampleResumeNext () On Error GoTo MyHandler 'Normal program code goes here. If an error 'occurs, control is transferred to the handler. 'When the handler is done, control resumes 'at the next line here. Exit Sub
MyHandler: 'Error is handled, and control resumes at the line 'after the statement that caused the error. Resume Next
End Sub
- In this example, control returns to the DoPrompt label after the error handler executes.
Sub SampleResumeToLabel () On Error GoTo MyHandler DoPrompt: 'Normal program code goes here. If an error occurs, 'control is transferred to the handler. Exit Sub
MyHandler: 'Error is handled, and then control is transferred 'to the top of the macro, at the DoPrompt label. Resume DoPrompt
End Sub
|