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 name-space of the .NET Framework class library to check whether a file exists on CD before it's opened:
If File.Exists("d:\fileopen.bmp") Then PictureBox1.Image = _ 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 error handlers? The answer depends on how often you think a problem will occur with the statements that you plan to use. If an exception or run-time error will occur somewhat infrequently—say less than 25 percent of the time a particular piece of code is executed—using an error handler is probably the most efficient way to go. Error handlers are also 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. However, if there's a real likelihood that a piece of code will produce a run-time error more than 25 percent of the time, 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. In the end, it probably makes the most sense to use a combination of defensive programming and structured error handling techniques in your code.