Error Handling

 

Error handling is essential to all professional applications.  Any number of run-time errors can occur, and if your program does not trap them, the VB default action is to report the error and then terminate the program (often resulting in the end user calling you and complaining, "Your program kicked me out!").

 

By placing error-handling code in your program, you can trap a run-time error, report it, and let the user continue.  Sometimes the user will be able to correct the error and sometimes not, but simply allowing the program to crash is not acceptable.

 

You should generally place error-handling code in any Sub or Function that accesses files or databases.  Your code will typically interrogate the Number and Description properties of the built-in VB Err object in an error-handling routine set up with the On Error statement. 

 

In this section, we will look at the following statements:

 

On Error GoTo label

 

On Error Resume Next

 

Following is a brief tutorial in error-handling. To perform this tutorial, you should have a floppy disk handy.  Also, in the VB IDE, make sure that the Break on Unhandled Errors option is set under Tools à Options à General.

 

STEPS:

 

1.   Start a new project.

 

2.   Place four command buttons on the form. Name them and set their Captions as follows:

 

Name              Caption

cmdCrash          Crash

cmdGoToLabel      GoTo Label

cmdGoTo0          GoTo 0

cmdResumeNext     Resume Next

 

Your form should look something like this:

 

 

 

3.         Code the cmdCrash_Click event as follows:

 

            Private Sub cmdCrash_Click()

    Open "A:\JUNK.TXT" For Input As #1

                MsgBox "File was opened successfully"

                 Close #1     

            End Sub

 

4.         Place your floppy disk in the A: drive.  Run the program and click the Crash button.  Assuming that you do not have a file called "JUNK.TXT" on your A: disk, the program will "bomb" with the code/message "53 – File Not Found".  If you don't have a disk in drive A:, the code/message will be "71 – Disk Not Ready".

           

5.         Code the cmdGoToLabel_Click event: Copy and paste the code from the Crash sub, and add statements so that the cmdGoToLabel_Click Sub looks like the following (the new statements are shown in bold):

     

Private Sub cmdGoToLabel_Click()

 

    On Error GoTo OpenFileError   

    Open "A:\JUNK.TXT" For Input As #1

    MsgBox "File was opened successfully"

    Close #1   

    Exit Sub

   

OpenFileError:

    MsgBox "The following error occured: " & vbNewLine _

         & "Error # " & Err.Number & vbNewLine _

         & Err.Description, _

           vbCritical, _

           "Open Error"

 

End Sub

 

6.         Run the program and click the "GoTo Label "button.  Notice that your error message comes up, but the program does not crash.  Note that the error-handling code accessed the Number and Description properties of the VB Err Object.

 

In general, the basic structure of a sub or function that performs error handling is as follows:

 

      Sub MySub()

 

          On Error GoTo MyErrorHandler

 

          Statements that do something useful

 

          Exit Sub

 

      MyErrorHandler:

 

          Error-handling statements

 

      End Sub

 

7.         Related to the On Error GoTo label statement is On Error GoTo 0, which turns off, or cancels, a previous On Error statement.  You would typically use On Error GoTo 0 while you are testing a program, so that you can determine exactly what statement caused the error when the program crashes in the design environment.  You would typically remove this statement before you did a final compile.

 

In the cmdGoTo0_Click event for this button, copy and paste the code from the cmdGoToLabel_Click sub, and just add one statement.  In between the "On Error" statement and the "Open" statement, add the statement: On Error GoTo 0.  The code should look like this:

 

Private Sub cmdGoTo0_Click()

 

    On Error GoTo OpenFileError

    On Error GoTo 0   

    Open "A:\JUNK.TXT" For Input As #1

    MsgBox "File was opened successfully"

    Close #1   

    Exit Sub

   

OpenFileError:

    MsgBox "The following error occured: " & vbNewLine _

         & "Error # " & Err.Number & vbNewLine _

         & Err.Description, _

           vbCritical, _

           "Open Error"

 

End Sub

 

            Run the program and click the GoTo 0 button.  The program crashes.  The On Error GoTo 0 statement canceled out the On Error statement above it, as if you had no error handling statements at all.

 

8.         Another format of the On Error statement is On Error Resume Next, which allows you to handle the error "in-line", without branching to a label.  "Resume Next" tells VB to keep going, even if an error occurs (but VB will still set the values of the Err object).  Therefore, if you use On Error Resume Next, you should test the value of Err.Number after any statement that could cause an error, and take appropriate action if Err.Number is non-zero (an Err.Number value of zero means that no error occurred).

 

In the cmdResumeNext_Click event procedure, place the following code.  Note: This code uses the Clear method of the Err object, which resets the object (including the Number property) – this is necessary because the error checking is done in a loop and Err.Number needs to be reset on each iteration of the loop so that accurate testing of Err.Number can take place.

 

 

Private Sub cmdResumeNext_Click()

 

           Dim intResponse     As Integer

           Dim blnFileOpenedOK As Boolean

 

     On Error Resume Next

   

     Do

        intResponse = MsgBox("Insert the disk containing 'JUNK.TXT' in drive A", _

                             vbOKCancel, _

                             "Insert Disk")

        If intResponse = vbCancel Then Exit Sub

        Err.Clear

        Open "A:\JUNK.TXT" For Input As #1

        Select Case Err.Number

            Case 0

                blnFileOpenedOK = True

            Case 71

                MsgBox "The drive is not ready.", _

                       vbExclamation, _

                       "Drive Error"

            Case 53

                MsgBox "File 'JUNK.TXT' not found on drive A.", _

                       vbExclamation, _

                       "File Not On Disk"

            Case Else

                MsgBox "The following error occured: " & vbNewLine _

                     & "Error # " & Err.Number & vbNewLine _

                     & Err.Description, _

                       vbCritical, _

                       "Open Error"

           End Select

    Loop Until blnFileOpenedOK

   

    MsgBox "File was opened successfully"

    Close #1

 

End Sub

 

9.         Pop your disk out of drive A and run the program.

 

Click the Resume Next button. You get the "drive not ready" message.

 

Pop your disk back into the drive and click OK.

 

Click OK to the "insert disk" message.  You get the "File not found" message.

 

Click OK, then click Cancel in response to the "Insert disk" message.

 

            Minimize VB.

 

            Open the My Computer application off of the desktop, then double-click the A-drive icon..

 

            In the drive A window, right-click the mouse and select New from the popup menu.  From the next menu, click Text document.  Rename the new text document JUNK.TXT.

 

            Close the A-drive and My Computer windows.

 

            From the taskbar, resurrect VB and your program.  Click the Resume Next button.  You should get the message "File was opened successfully."  Click any of the other buttons; they should all produce the same result.

 

            Save your program.

 

            Download the VB project code for the example above here.

 

 

FYI:      Sometimes the Resume Next form of the On Error statement is used to deliberately ignore an error.  For example, suppose you want to drop a table from a database.  The table may or may not already exist.  If the table does not exist and you tell the system to drop it, an error will occur – but this is an error you can ignore, because if the table does not exist, who cares? - you want to delete it anyway!  The code might look something like this:

 

Sub MySub()

' Drop the table if it exists

On Error Resume Next

dbMyDB.Execute "DROP TABLE MyTable"

' Resume regular error-handling

On Error GoTo MyErrHandler

' other processing here

Exit Sub

MyErrHandler:

      ' error processing

End Sub

 

The following example shows how error-handling code could be incorporated into one of the previous file processing examples that we looked at earlier. To try this example, copy the "print" version of the EMPLOYEE.DAT file onto a floppy disk, start a new VB project, place the code below into the Form_Activate event, and run (Note – use the Activate instead of the Load event here, because you cannot Print to a Form until after the Load event has completed).  If desired, test conditions that would cause errors.

 

Private Sub Form_Activate()

 

    Dim strEmpFileName   As String

    Dim strBackSlash     As String

    Dim intEmpFileNbr    As Integer

 

    Dim strEmpRecord     As String

    Dim strEmpName       As String

    Dim intDeptNbr       As Integer

    Dim strJobTitle      As String

    Dim dtmHireDate      As Date

    Dim sngHrlyRate      As Single

 

    Dim strErrMsg        As String

    Dim blnFileOpenedOK  As Boolean

 

    On Error Resume Next

   

    strEmpFileName = "A:\EMPLOYEE.DAT"

    intEmpFileNbr = FreeFile

   

    Do

        Err.Clear

        Open strEmpFileName For Input As #intEmpFileNbr

        Select Case Err.Number

            Case 0

                blnFileOpenedOK = True

            Case 71

              strErrMsg = "The drive is not ready."

            Case 53

                 strErrMsg = "The file '" & strEmpFileName & "' was not found."

            Case Else

                 strErrMsg = "The following error occured: " & vbNewLine _

                           & "Error # " & Err.Number & vbNewLine & Err.Description

          End Select

          If Err.Number <> 0 Then

            If MsgBox(strErrMsg, vbRetryCancel, "Open Error") = vbCancel Then

                Exit Sub

            End If

          End If

    Loop Until blnFileOpenedOK

   

    Do Until EOF(intEmpFileNbr)

        Line Input #intEmpFileNbr, strEmpRecord

        strEmpName = Left$(strEmpRecord, 20)

        intDeptNbr = Val(Mid$(strEmpRecord, 21, 4))

        strJobTitle = Mid$(strEmpRecord, 30, 21)

        dtmHireDate = CDate(Mid$(strEmpRecord, 51, 10))

        sngHrlyRate = Val(Mid$(strEmpRecord, 61, 5))

        Print strEmpName; _

              Tab(25); Format$(intDeptNbr, "@@@@"); _

              Tab(35); strJobTitle; _

              Tab(60); Format$(dtmHireDate, "mm/dd/yyyy"); _

              Tab(71); Format$(Format$(sngHrlyRate, "Standard"), "@@@@@@@")

    Loop

 

    Close #intEmpFileNbr

 

End Sub

 

Download the VB project code for the example above here.