Chapter 21. Handling Errors

The best way to handle errors is to not give the user the chance 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 DVD, CD, or flash drive 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 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, the code adds the wrong numbers.

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 ...

Get Stephens' Visual Basic® Programming 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.