
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.