How to Handle Errors

See Also

Ideally, Visual Basic procedures wouldn't need error-handling code at all. Reality dictates that hardware problems or unanticipated actions by the user can cause run-time errors that halt your code, and there's usually nothing the user can do to resume running the application. Other errors might not interrupt code, but they can cause it to act unpredictably.

For example, the following procedure returns true if the specified file exists and false if it does not, but doesn't contain error-handling code:

Function FileExists (filename) As Boolean
   FileExists = (Dir(filename) <> "")
End Function

The Dir function returns the first file matching the specified file name (given with or without wildcard characters, drive name, or path); it returns a zero-length string if no matching file is found.

The code appears to cover either of the possible outcomes of the Dir call. However, if the drive letter specified in the argument is not a valid drive, the error "Device unavailable" occurs. If the specified drive is a floppy disk drive, this function will work correctly only if a disk is in the drive and the drive door is closed. If not, Visual Basic presents the error "Disk not ready" and halts execution of your code.

To avoid this situation, you can use the error-handling features in Visual Basic to intercept errors and take corrective action. (Intercepting an error is also known as trapping an error.) When an error occurs, Visual Basic sets the various properties of the error object, Err, such as an error number, a description, and so on. You can use the Err object and its properties in an error-handling routine so that your application can respond intelligently to an error situation.

For example, device problems, such as an invalid drive or an empty floppy disk drive, could be handled by the following code:

Function FileExists (filename) As Boolean
   Dim Msg As String
   ' Turn on error trapping so error handler responds 
   ' if any error is detected.
   On Error GoTo CheckError   
      FileExists = (Dir(filename) <> "")
      ' Avoid executing error handler if no error 
      ' occurs.
      Exit Function

CheckError:         ' Branch here if error occurs.
   ' Define constants to represent intrinsic Visual
   ' Basic error codes. 
   Const mnErrDiskNotReady = 71, _
   mnErrDeviceUnavailable = 68
   ' vbExclamation, vbOK, vbCancel, vbCritical, and
   ' vbOKCancel are constants defined in the VBA type
   ' library.
   If (Err.Number = MnErrDiskNotReady) Then
      Msg = "Put a floppy disk in the drive " 
      Msg = Msg & "and close the door."
      ' Display message box with an exclamation mark
      ' icon and with OK and Cancel buttons.
      If MsgBox(Msg, vbExclamation & vbOKCancel) = _
      vbOK Then
         Resume
      Else
         Resume Next
      End If
   ElseIf Err.Number = MnErrDeviceUnavailable Then
      Msg = "This drive or path does not exist: "
      Msg = Msg & filename
      MsgBox Msg, vbExclamation
      Resume Next
   Else
      Msg = "Unexpected error #" & Str(Err.Number)
      Msg = Msg & " occurred: " & Err.Description
      ' Display message box with Stop sign icon and
      ' OK button.
      MsgBox Msg, vbCritical
      Stop
   End If
   Resume
End Function

In this code, the Err object's Number property contains the number associated with the run-time error that occurred; the Description property contains a short description of the error.

When Visual Basic generates the error "Disk not ready," this code presents a message telling the user to choose one of two buttons — OK or Cancel. If the user chooses OK, the Resume statement returns control to the statement at which the error occurred and attempts to re-execute that statement. This succeeds if the user has corrected the problem; otherwise, the program returns to the error handler.

If the user chooses Cancel, the Resume Next statement returns control to the statement following the one at which the error occurred (in this case, the Exit Function statement).

Should the error "Device unavailable" occur, this code presents a message describing the problem. The Resume Next statement then causes the function to continue execution at the statement following the one at which the error occurred.

If an unanticipated error occurs, a short description of the error is displayed and the code halts at the Stop statement.

The application you create can correct an error or prompt the user to change the conditions that caused the error. To do this, use techniques such as those shown in the preceding example. The next section discusses these techniques in detail.

For More Information   See "Guidelines for Complex Error Handling" in "Error-Handling Hierarchy" later in this chapter for an explanation of how to use the Stop statement.