Handling Errors
The best way to handle errors is to not give the user the ability to make them in the first place. For
example, suppose a program can take purchase orders for between 1 and 100 reams of paper. If
the program lets you specify the quantity by using a
NumericUpDown control with Minimum = 1
and
Maximum = 100, you cannot accidentally enter invalid values like –5 or 10,000.
Sometimes, however, it’s hard to build an interface that protects against all possible errors. For
example, if the user needs to type in a numeric value, you need to worry about invalid inputs
such as 1.2.3 and ten. If you write a program that works with files, you can’t always be sure the
file will be available when you need it. For example, it might be on a CD or floppy disk that has
been removed, or it might be locked by another program.
In this lesson, you learn how to deal with these kinds of unexpected errors. You learn how to
protect against invalid values, unavailable files, and other problems that are difficult or impos-
sible to predict in advance.
ERRORS AND EXCEPTIONS
An error is a mistake. It occurs when the program does something incorrect. Sometimes an
error is a bug, for example, if the code just doesn’t do the right thing.
Sometimes an error is caused by circumstances outside of the program’s control. If the program
expects the user to enter a numeric value in a textbox but the user types 1.2.3, the program won’t
be able to continue its work until the user fixes the problem.
Sometimes you can predict when an error may occur. For example, if a program needs to open
a file, there’s a chance that the file won’t exist. In predictable cases such as this one, the program
should try to anticipate the error and protect itself. In this case, it should check to see if the file
exists before it tries to open it. It can then display a message to the user and ask for help.
Other errors are hard or impossible to predict. Even if the file exists, it may be locked by
another program. The user entering invalid data is another example. In those cases, the
program may need to just try to do its job. If the program tries to do something seriously
invalid, it will receive an exception.
21
596906book.indd 251 4/8/10 7:40:26 AM