Microsoft Access 2010 Bible

(Rick Simeone) #1

Chapter 23: Handling Errors and Exceptions


827


Caution
The worst type of situation occurs when the values returned by the program appear to be correct but are, in
fact, wrong.


Using VBA error-handling techniques, you can add code to your applications to prevent unex-
pected crashes or inconsistent behavior. Unfortunately, there is little you can do to correct a poorly
programmed application, other than updating the application’s code to correct the problem. If cal-
culations are being performed incorrectly, there is little that the VBA engine can do to correct these
types of errors. VBA code can be utilized to gracefully cater to unexpected behavior in Access.

Microsoft Access provides several basic programming elements used for catering to errors, includ-
ing the following:

l The Err object

l (^) VBA error-handling statements
l The Error event
l (^) The ADO Errors collection
The following sections detail each of these program elements. As you read the following sections,
notice that there are two types of errors in Access applications:
l Application errors: Application errors are generally caused by something in the user
interface (incorrect data entry by the user, for example).
l Database errors: Database errors are thrown by the database engine (record locking
problems, for instance). Database errors are generally caught by the Error event behind
bound forms or are thrown by ActiveX Data Objects (ADO).
The Err object
The Err object is a part of the VBA language and is always present in Access applications. When
an application error occurs, information about the error is stored in the Err object, enabling you
to examine the Err object and learn the details of the error.
The Err object contains information about only the most recent error and does not contain infor-
mation about any other error. This means that, if the current error was the result of a cascade of
other errors, the only information available to you is the most recent error. When a new error
occurs, the Err object is cleared and updated to include information about that most recent error.
The Err object has several properties, including Number, Description, and Source. The
Number is the VBA number of the error. Description gives you a little more information about
the error. The Source property is not normally very useful in Access applications, because it iden-
tifies the VBA project that generated the error, and in Access applications, the project name is the
same as the name of the Access application by default.

Free download pdf