Handling Unexpected Errors

Unexpected errors are errors that you have no way of predicting, and that under normal circumstances should not occur. When your application encounters an unexpected error (for example, divide by zero or a missing object), and no error handling is in effect, Access will display an error message like the one above, and then abruptly end the procedure.

The goal of error handling in this case is not to solve the problem the error is indicating; there's nothing you can do about it now. Your code has tripped on an error and fallen down.

The only thing you can do is let the user know what happened calmly and in plain language. Figure 9-2 is an example of what your error message might look like.

An error lias occurred in this application. Please contact your technical support person and tell them this information:

An error lias occurred in this application. Please contact your technical support person and tell them this information:

Error Number 11, Division by zero

Figure 9-2

There are several differences between the error message Access shows and the "handled" error message you can show:

□ The title of the message box can be specified by you instead of displaying "Microsoft Visual Basic" or "Microsoft Access."

□ You can show an icon to have a stronger impact.

□ You can add an explanation and text. You can even mention your phone number or other contact information.

□ You can format the error message with blank lines, commas, and so on.

□ Your user can't enter debug mode.

Some errors can be expected during normal operation. One error that you can safely predict will happen in your application is when the On Open event of a report is cancelled. This can happen when you display a form to prompt the user for selection criteria during the On Open event, and the user decides to cancel the report. This technique is described in Chapter 14.

There are other errors that you can expect. Maybe you expect a certain file to be on the hard drive, but it isn't. Maybe you expect a form to be open, but somehow it has been closed. These kinds of errors can be absorbed by your application if possible, never allowing the user to see them.

In these situations, your code should just ignore the error and keep going. To do this, you add an If statement to check if the error number matches the number you expect. If it matches, you can just Resume Next to continue to the next line of code. If it doesn't match, you can drop into your normal error handling.

Now we'll move into some basic error handling code that can be used for handling both expected and unexpected errors in your application.

Let's start with the basics. Here is some code that you could add to every procedure to build in easy, no-frills error handling.

0 0

Post a comment