Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

234 Part II Programming Fundamentals


Test the error handler


  1. Remove the CD or DVD from drive D, and then click the Start Debugging button to run
    the program.

  2. Click the Check Drive button.


Instead of stopping program execution, Visual Basic invokes the Catch statement, which
displays the following message box:


  1. Click OK, and then click the Check Drive button again.


The program displays the message box again, asking you to insert the disc in drive D.
Each time there’s a problem loading the file, this message box appears.


  1. Insert the disc in drive D, wait a moment for the system to recognize the CD or DVD
    (close any windows that appear when you insert the disc), click OK, and then click the
    Check Drive button again.
    The bitmap graphic appears in the picture box, as expected. The error handler has
    completed its work effectively—rather than the program crashing inadvertently, it’s
    told you how to correct your mistake, and you can now continue working with the
    application.

  2. Click the Close button on the form to stop the program.


It’s time to learn some of the variations of the Try... Catch error handler.

Using the Finally Clause to Perform Cleanup Tasks


As with the syntax description for Try... Catch noted earlier in the chapter, you can use
the optional Finally clause with Try... Catch to execute a block of statements regardless
of how the compiler executes the Try or Catch blocks. In other words, whether or not the
Try statements produced a run-time error, there might be some code that you need to run
each time an error handler is finished. For example, you might want to update variables or
properties, display the results of a computation, close database connections, or perform
“cleanup” operations by clearing variables or disabling unneeded objects on a form.

The following exercise demonstrates how the Finally clause works, by displaying a second
message box whether or not the FromFile method produces a run-time error.
Free download pdf