Chapter 9 Trapping Errors by Using Structured Error Handling 243
System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")
Else
MsgBox("Cannot find fileopen.bmp on drive D.")
End If
This If... Then statement isn’t an actual error handler because it doesn’t prevent a run-time
error from halting a program. Instead, it’s a validation technique that some programmers
call defensive programming. It uses a handy method in the .NET Framework class library to
verify the intended file operation before it’s actually attempted in the program code. And in
this particular case, testing to see whether the file exists with the .NET Framework method
is actually faster than waiting for Visual Basic to issue an exception and recover from a
run-time error using an error handler.
Note To get this particular program logic to work, the following statement must be included
in the declarations section at the very top of the form’s program code to make reference to the
.NET Framework class library that’s being invoked:
Imports System.IO
For more information about utilizing the Imports statement to use the objects, properties,
and methods in the .NET Framework class libraries, see Chapter 5, “Visual Basic Variables and
Formulas, and the .NET Framework .”
When should you use defensive programming techniques, and when should you use
structured error handlers? The answer is really that you should use a combination of defensive
programming and structured error-handling techniques in your code. Defensive programming
logic is usually the most efficient way to manage potential problems. As I mentioned earlier
when discussing the If... Then code block, the File.Exists method is actually faster than using
a Try... Catch error handler, so it also makes sense to use a defensive programming technique
if performance issues are involved. You should use defensive programming logic for errors
that you expect to occur frequently in your program. Use structured error handlers for errors
that you don’t expect to occur very often. Structured error handlers are essential if you have
more than one condition to test and if you want to provide the user with numerous options
for responding to the error. Structured error handlers also allow you to gracefully handle errors
that you aren’t even aware of.
One Step Further: The Exit Try Statement
You’ve learned a lot about error handlers in this chapter; now you’re ready to put them to
work in your own programs. But before you move on to the next chapter, here’s one more
syntax option for Try... Catch code blocks that you might find useful: the Exit Try statement.
Exit Try is a quick and slightly abrupt technique for exiting a Try... Catch code block
prematurely. If you’ve written Visual Basic programs before, you might notice its similarity to
the Exit For and Exit Sub statements, which you can use to leave a structured routine early.