Error Handling


The previous course discussed various approaches to data verification and suggested ways to check a program's data to prevent processing errors.  Some errors are not possible to catch through normal code, but instead required specialized error handling techniques. For example, certain calculations may produce underflow (number too small) or overflow (number too large) errors, and other code may be subject to hardware errors, such as file not found or no diskette in a disk drive.  These are known as synchronous errors, and include memory exhaustion, out-of-bounds array index, divide by zero, and arithmetic overflow.  If the error is severe and recovery is not possible, the program can be exited gracefully by closing all files and notifying the user.

If a program is equipped with an error handler and an error is raised, control is transferred to the error handler. The code in the error handler that is provided to deal with such an error is executed and then the program continues (if the error handler indicates that it should do so.) If an error handler is not provided and an error is raised, an error message appears in a modal dialog before the program terminates. 


Visual Basic provides a built-in Err object that is present in all programs.  When an error occurs, the properties of the Err object are updated with information about the error.  The table below shows the properties of the Err object.

Property Data Type                   Description
Number Long Internal error determined by VB or a component with which the program interacts.
Description String Error message text describing the error.
Source String File name where the error was raised or the source of the error if the error was outside the application.

Error handlers are activated with an On Error GoTo program-label statement, often at the beginning of a sub or function.  This statement indicates to VB which statements to execute if an error occurs in the statements that follow.  If one of the statements following the On Error statement causes an error, processing will jump to the line labeled program-label.  The program-label is a programmer-selected name that indicates the beginning of the error-handler code, for example, On Error GoTo GeneralErrHandler.

The program must include code to be executed when an error is encountered.  This code follows a line containing program-label.  The code in the error handler can check for various types of errors and display appropriate error messages or attempt to correct the problem, or it can simply display a message that indicates the nature of the error.  A program can test for specific error numbers, or display some of all of the property values in an error message.  The following call to a MsgBox function would display all three of the property values:  

    GeneralErrHandler:
        Call MsgBox (CStr(Err.Number) & ": " & Err.Description & " - " & Err.Source)

When an error sets the values of the Err properties, that remain available until 

VB needs to be notified that the error handling section has terminated.  The Resume or Resume Next statements can all be used for this purpose.


The following code segments demonstrate different approaches to writing an error handling routine.  Each reacts to invalid input in the following program:

 

In the first code segment, a generic error message is displayed for any error that is encountered.  Notice the positioning of the On Error statement.  Note also the need for the Exit Sub statement directly before the error handler.  Without it, the error handler would be executed even when all input is valid.  Exit Subs are also required at the end of error handlers if multiple error handlers are included.


     Private Sub cmdMultiply_Click( )
          Dim Answr As Long

          On Error GoTo MultErrHandler
          Answr = CLng(txtNum1.Text) * CLng(txtNum2.Text)
          lblAnswer.Caption = CStr(Answr)
     Exit Sub

     MultErrHandler:
          Call MsgBox("Error trying to multiply")
     End Sub

Here is the message box that results from invalid input:


In the next code segment, an error message made up of the error number, description, and source is displayed for any error that is encountered.  


     Private Sub cmdMultiply_Click( )
          Dim Answr As Long

          On Error GoTo MultErrHandler
          Answr = CLng(txtNum1.Text) * CLng(txtNum2.Text)
          lblAnswer.Caption = CStr(Answr)
     Exit Sub

     MultErrHandler:
          Call MsgBox(CStr(Err.Number) & ": " & Err.Description & " - " & Err.Source)
     End Sub


The final code segment demonstrates the ability of error handlers to react to certain errors by generating more specific error messages.  The value of the Err.Number property can be used to distinguish between errors.  Additional errors can be found by looking up "Trappable Errors" in VB help.


     Private Sub cmdMultiply_Click( )
          Dim Answr As Long

          On Error GoTo MultErrHandler
          Answr = CLng(txtNum1.Text) * CLng(txtNum2.Text)
          lblAnswer.Caption = CStr(Answr)
     Exit Sub

     MultErrHandler:
          Select Case Err.Number
               Case 6
                         Call MsgBox("Overflow while multiplying." & vbCrLf _
                                                  & "Numbers too large--try again.")
               Case 13
                         Call MsgBox("Error converting numbers." & vbCrLf _
                                                  & "Correct and try again.")
               Case Else
                         Call MsgBox(Err.Number & " -- " & Err.Description)
          End Select
     End Sub

 

                               


When a problem is uncovered, various actions can be taken:

Regardless of the error handling approach selected, the user should always be notified of both the problem and the corrective action taken by the program.  MsgBox and InputBox controls can be used, as can labels.