Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

240 Part II Programming Fundamentals


Retries variable at the top of the form’s program code so that it has scope throughout all
the form’s event procedures. The Retries variable is then incremented and tested in the
Catch code block. The number of retries can be modified by simply changing the “2” in the
statement, as shown here:

If Retries <= 2

Use a variable to track run-time errors


  1. In the Code Editor, scroll to the top of the form’s program code, and directly below the
    Public Class Form1 statement, type the following variable declaration:
    Dim Retries As Short = 0
    Retries is declared as a Short integer variable because it won’t contain very big numbers.
    It’s assigned an initial value of 0 so that it resets properly each time the program runs.

  2. In the Button1Click event procedure, edit the Try... Catch error handler so that it looks
    like the following code block:
    Try
    PictureBox1.Image =

    System.Drawing.Bitmap.FromFile("d:\fileopen.bmp")
    Catch
    Retries += 1
    If Retries <= 2 Then
    MsgBox("Please insert the disc in drive D!")
    Else
    MsgBox("File Load feature disabled")
    Button1.Enabled = False
    End If
    End Try
    The Try block tests the same file-opening procedure, but this time, if an error occurs,
    the Catch block increments the Retries variable and tests the variable to be sure that
    it’s less than or equal to 2. The number 2 can be changed to allow any number of
    retries—currently it allows only two run-time errors. After two errors, the Else clause
    is executed, and a message box appears indicating that the file-loading feature has
    been disabled. The Check Drive button is then disabled—in other words, dimmed
    and rendered unusable for the remainder of the program.


Tip This revised version of the error handler that you have been building has been renamed
Disc Drive Handler and is stored in the C:\Vb10sbs\Chap09\Disc Drive Handler folder. You
may notice the new project title in the title bar of your message boxes, but otherwise the
project is the same as what you have been experimenting with thus far. (I’ve simply saved the
revised version so that you can open it later if you want .)


  1. Click the Start Debugging button to run the program.

  2. Remove the CD or DVD from drive D.

Free download pdf