One of the most powerful features of Visual Basic is its ability to trap all errors, analyze them, and take corrective action. In a well-designed production application, the
Use an On Error statement to enable error trapping, establish the procedure to handle error trapping (the error handler), skip past any errors, or
On Error
{
GoTo
lineID
Resume
Next
GoTo 0}
Use a GoTo lineID clause to establish a code block in your procedure that handles any error. The lineID can be a line number or a label.
Use a Resume Next clause to trap errors but skip over any statement that causes an error. You can call the Err function in a statement immediately following the statement that you suspect might have caused an error to see whether an error occurred. Err returns 0 if no error has occurred.
Use a GoTo 0 statement to turn off error trapping for the current procedure. If an error occurs, Visual Basic
In your error handling statements, you can examine the built-in Err variable (the error number associated with the error) to determine the exact nature of the error. You can use the Error function to examine the text of the error message associated with the error. If you use line
To trap errors but continue execution with the next statement, enter the following:
On Error Resume Next
To trap errors and execute the statements that follow the MyError: label when an error occurs, enter the following:
On Error GoTo MyError
To turn off error trapping in the current procedure, enter the following:
On Error GoTo 0
If you create and run the following function with zero as the second argument, such as MyErrExample(3,0), the function will trigger an error by attempting to divide by zero, trap the error, display the error in an error handling section, and then exit gracefully.
Public Function MyErrExample(intA As Integer, intB As Integer) As Integer ' Set an error trap On Error GoTo Trap_Error ' The following causes an error if intB is zero MyErrExample = intA / intB ExitNice: Exit Function Trap_Error: MsgBox "Something badhappened : " & Err & ", " & Error Resume ExitNice End Function