Chapter 9 Trapping Errors by Using Structured Error Handling 239
- Run the program again, and then click the Check Drive button.
The error handler displays the following error message:
Notice that I have used the Message property to display a short description of the
problem (“Out of memory .”) in the message box title bar. Using this property in your
error handler can give the user a clearer idea of what has happened.
- Click OK, and then click the Close button on the form to stop the program.
- Change the file name back to Fileopen .bmp in the FromFile method. (You’ll use it in the
next exercise .)
The Catch statement is very powerful. By using Catch in combination with the Exception
object and Message property, you can write sophisticated error handlers that recognize
and respond to several types of exceptions.
Raising Your Own Errors
For testing purposes and other specialized uses, you can artificially generate your own
run-time errors in a program with a technique called throwing, or raising, exceptions. To
accomplish this, you use the Throw statement. For example, the following syntax uses
the Throw statement to produce an exception and then handles the exception by using
a Catch statement:
Try
Throw New Exception("There was a problem")
Catch ex As Exception
MsgBox(ex.Message)
End Try
When you learn how to write your own procedures, you can generate your own errors
by using this technique and return them to the calling routine.
Specifying a Retry Period
Another strategy that you can use in an error handler is to try an operation a few times and
then disable it if the problem isn’t resolved. For example, in the following exercise, a
Try... Catch block employs a counter variable named Retries to track the number of times
the message “Please insert the disc in drive D!” is displayed, and after the second time, the
error handler disables the Check Drive button. The trick to this technique is declaring the