Avoiding run-time errors
Run-time errors can include many unforeseen events. You can’t handle all
run-time errors in your program. For example,
a storm that removes power
from the computer isn’t something that you can control. You need an uninter-
ruptible power supply (UPS) attached to the computer to handle that error.
Even so, such an error can result in data loss.
However, you can avoid other kinds of run-time errors. Input errors are one
of the most common run-time problems that you face when working with
VBA. In Chapter 5, I show some techniques
for avoiding run-time errors
caused by improper input. You can also use these techniques:
Check every input for data type, length, value, and meaning.
Provide easy-to-understand prompts for your application.
Make the prompts and error messages as specific as possible.
Offer to fix the problem automatically whenever possible.
Offer to retry the operation after you correct the error.
Reduce the chances of error by providing complete context-sensitive
help that includes examples and other resource information.
Checking the input is the most important task that your program can per-
form. If the
program needs a word as input, don’t accept a number. Ensure
that the length of the input matches expectations. This check is especially
important to avoid
buffer overrun,
which is a
condition where the program
receives too much input. Buffer overrun errors often make the news as secu-
rity breaches. If possible, look for specific values. Even if you don’t have spe-
cific
input values, check for strange characters or values that seem out of
place. It’s also possible in some cases to examine the meaning of the input. A
street address usually requires a street number and name. When you want to
ensure that the address information is correct, try
looking for this informa-
tion in the input.
Program resource problems are the second-most common source of run-time
errors. You might not have enough space on the hard drive to save a file, or
the program might not find a file that it needs. Checking for the resource
before you need it helps avoid the associated run-time error.
If the resource is
something that you can fix, such as a lack of hard drive space, include code
that allows you to perform this task and then ask the program to check again.
Errors can also creep into your applications when you don’t
include required
library references. A
library
is code that resides outside of your application.
The code might appear in many forms, but the form doesn’t really matter. All
you’re concerned about is the functionality that the library provides. You’ll
139
Do'stlaringiz bilan baham: