MS-Access / Getting Started

The Err Object

When a user encounters an error in your program, he should be provided with a clear, precise description of the problem and resolution. The Err object provides VBA programmers with an accessible means of finding or triggering Microsoft Windows-specific errors.

Essentially the Err (short for error) object maintains information about errors that occur in the current procedure. This information is stored in the form of properties. The most common of the Err properties follow:

  • Description contains a description of the current error.
  • Number contains the error number of the current error (0 to 65,535).
  • Source contains the name of the object that generated the error.

Table-1 contains just a few of VBA's more common trappable error numbers and descriptions.

Table-1 Common Error Numbers and Descriptions
Error Number 		Error Description
11 			Division by 0
53 			File Not Found
61 			Disk Full
71 			Disk Not Ready
76 			Path Not Found

In the next program example, use an error handler to check for division by 0.

Private Sub cmdDivide_Click()
    On Error GoTo ErrorBin

    MsgBox "Result is " & Val(txtOperand1.Value) _
    / Val(txtOperand2.Value)

    Exit Sub


    MsgBox "Error Number " & Err.Number & ", " & Err.Description

    Resume Next

End Sub

There may be times when an error occurs in your program that is similar to that of a given Err description, but does not trigger the specific Err number. The ability to trigger errors can be achieved through the Err object's Raise method.

The Raise method allows you to trigger a specific error condition, thus displaying a dialog box to the user. The Raise method takes a number as a parameter. For example, the following statement triggers a Disk Not Ready dialog box:

Err.Raise 71

Besides providing descriptive error messages, error handling prevents many unwanted problems for your users. In other words, error handling may prevent your program from crashing. Users expect an error for division by 0, but they don't expect division by 0 to crash their applications.

[Previous] [Contents] [Next]