The best way to avoid user 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 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 impossible to predict and prevent.
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 “seven,” the program won't be able to continue its work until the user fixes the problem. ...