Error Trapping

Error Trapping

See Also

You can use the On Error GoTo statement to trap errors and direct procedure flow to the location of error-handling statements within a procedure. For example, the following statement directs the flow to the ErrorHandler: label line:

On Error GoTo ErrorHandler

Be sure to give each error handler label in a procedure a unique name that will not conflict with any other element in the procedure, and make sure you append a colon to the name. Within the procedure, place the Exit Sub or Exit Function statement in front of the error handler label so that the procedure doesn't run the error-checking code if no error occurs.

Sub CausesAnError()
    ' Direct procedure flow.
    On Error GoTo ErrorHandler
    ' Raise division by zero error.
    Err.Raise 11
    Exit Sub

ErrorHandler:
    ' Display error information.
    MsgBox "Error number " & Err.Number & ": " & Err.Description
    ' Resume with statement following occurrence of error.
    Resume Next
End Sub

The Raise method of the Err object generates the specified error. The Number property of the Err object returns the number corresponding to the most recent run-time error; the Description property returns the corresponding message text for a given error.

Notes

For more information about setting error traps and writing error-handling statements, see Chapter 9, "Error Handling and Debugging," in the OPG9TBD. For information about how to obtain the OPG9TBD, click .