Chapter 9 Trapping Errors by Using Structured Error Handling 233
Writing a Disc Drive Error Handler
The problem with the Disc Drive Error program isn’t that it somehow defies the
inherent capabilities of Visual Basic to process errors. We just haven’t specified what
Visual Basic should do when it encounters an exception that it doesn’t know how
to handle. The solution to this problem is to write a Try... Catch code block that
recognizes the error and tells Visual Basic what to do about it. You’ll add this error
handler now.
Use Try... Catch to trap the error
- Display the Button1_Click event procedure if it isn’t visible in the Code Editor.
You need to add an error handler to the event procedure that’s causing the problems.
As you’ll see in this example, you actually build the Try... Catch code block around the
code that’s the potential source of trouble, protecting the rest of the program from
the run-time errors that it might produce.
- Modify the event procedure so that the existing FromFile statement fits between Try
and Catch statements, as shown in the following code block:
Try
PictureBox1.Image = _
System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")
Catch
MsgBox("Please insert the disc in drive D!")
End Try
You don’t need to retype the FromFile statement—just type the Try, Catch, MsgBox,
and End Try statements above and below it. If Visual Studio adds Catch, variable
declaration, or End Try statements in the wrong place, simply delete the statements and
retype them as shown in the book. (The Code Editor tries to be helpful, but its Auto
Complete feature sometimes gets in the way .)
This program code demonstrates the most basic use of a Try... Catch code block. It
places the problematic FromFile statement in a Try code block so that if the program
code produces an error, the statements in the Catch code block are executed. The
Catch code block simply displays a message box asking the user to insert the required
disc in drive D so that the program can continue. This Try... Catch code block contains
no Finally statement, so the error handler ends with the keywords End Try.
Again, if you are using a removable storage device or media associated with a
different drive letter, you would make those changes in the statements that you
just typed.