Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 9 Trapping Errors by Using Structured Error Handling 235


Use Finally to display a message box


  1. Display the Button1_Click event procedure, and then edit the Try... Catch code block so
    that it contains two additional lines of code above the End Try statement. The complete
    error handler should look like this:


Try
PictureBox1.Image = _
System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")
Catch
MsgBox("Please insert the disc in drive D!")
Finally
MsgBox("Error handler complete")
End Try
The Finally statement indicates to the compiler that a final block of code should be
executed whether or not a run-time error is processed. To help you learn exactly how
this feature works, I’ve inserted a MsgBox function to display a test message after
the Finally statement. Although this simple use of the Finally statement is helpful for
testing purposes, in a real program you’ll probably want to use the Finally code block
to update important variables or properties, display data, or perform other cleanup
operations.


  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.


The error handler displays a dialog box asking you to insert the disc in drive D.


  1. Click OK.


The program executes the Finally clause in the error handler, and the following message
box appears:


  1. Click OK, insert the disc in drive D, and then click the Check Drive button again.


The file appears in the picture box as expected. In addition, the Finally clause is
executed, and the “Error handler complete” message box appears again. As I noted
earlier, Finally statements are executed at the end of a Try... Catch block whether or
not there’s an error.


  1. Click OK, and then click the Close button on the form to stop the program.

Free download pdf