242 Part II Programming Fundamentals
The error handler has responded to the disc drive problem by allowing the user a few
tries to fix the problem, and then it has disabled the problematic button. (In other
words, the user can no longer click the button .) This disabling action stops future
run-time errors, although the program might no longer function exactly as it was
originally designed.
- Click the Close button on the form to stop the program.
Using Nested Try Catch Blocks
You can also use nested Try... Catch code blocks in your error handlers. For example, the
following disc drive error handler uses a second Try... Catch block to retry the file open
operation a single time if the first attempt fails and generates a run-time error:
Try
PictureBox1.Image = _
System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")
Catch
MsgBox("Insert the disc in drive D, then click OK!")
Try
PictureBox1.Image = _
System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")
Catch
MsgBox("File Load feature disabled")
Button1.Enabled = False
End Try
End Try
If the user inserts the disc in the drive as a result of the message prompt, the second Try
block opens the file without error. However, if a file-related run-time error still appears, the
second Catch block displays a message saying that the file load feature is being disabled,
and the button is disabled.
In general, nested Try... Catch error handlers work well so long as you don’t have too many
tests or retries to manage. If you do need to retry a problematic operation many times, use
a variable to track your retries, or develop a function containing an error handler that can
be called repeatedly from your event procedures. (For more information about creating
functions, see Chapter 10 .)
Comparing Error Handlers with Defensive
Programming Techniques
Error handlers aren’t the only mechanism for protecting a program against run-time errors. For
example, the following program code uses the File.Exists method in the System.IO namespace
of the .NET Framework class library to check whether a file exists on CD or DVD before it’s
opened:
If File.Exists("d:\fileopen.bmp") Then
PictureBox1.Image = _