Lesson 5: Debugging and Error Handling

Lesson Objectives

Upon completion of this lesson, the participant will be able to:

Some Topics to be introduced in this lesson include:

Testing and Debugging Code

Types of Errors

There are three types of errors in programming:

  • Language errors - These errors result from incorrectly constructed code. VB detects these errors automatically when the programmer enters the line or moves off the line, or immediately before the code executes.
  • Run-time errors - These errors occur when a statement attempts an operation that is impossible to carry out. The code may be syntactically correct but, because of the current conditions, is not an appropriate operation
  • Logic errors - The code has neither language or runtime errors but does not perform in the manner in which it was intended.
  • VB can provide assistance with language and run-time errors by alerting the programmer with a message describing the type of error. Logic errors are more difficult to debug because no errors are detected by VB during execution.

    Debugging Interface

    VB includes several tools to assist the programmer in debugging and testing code. The first is the Debug window. Using the Debug window, the programmer can monitor the values of expressions and variables while stepping through each statement in the code.

    Also, the Visual Basic toolbar includes buttons for stepping through code and adding breakpoints and watches to code. (These features are discussed later in this lesson.)

    Break Mode

    The following tasks are available while in break mode:

  • Determine which active procedures have been called.
  • Watch the values of variables, properties, and statements.
  • Change the values of variables and properties.
  • Run Visual Basic statements immediately.
  • Manually control the line-by-line execution of the code.
  • When in break mode, the Debug window appears and the programmer has access to a variety of tools. When the following occurs, VB switches to break mode:

  • Choosing one of the Step buttons in the Tools Macro dialog to execute a procedure.
  • Execution reaches a line that contains a breakpoint. A breakpoint is set by selecting the line where the break should occur and pressing the Toggle Breakpoint button. (Or, select the Run Toggle Breakpoint command.)
  • Execution reaches a Stop statement.
  • A break expression defined in the Add Watch dialog changes or becomes true. (Discussed later in this lesson.)
  • An untrapped run-time error occurs.
  • The Debug button is selected in the dialog that appears after CTRL-BREAK or ESC is pressed.
  • Unlike Visual Basic 3.0, it is not possible to edit code in the Debug window in VB.

    Stepping Through Code

    While the Debug window is visible, the programmer may step through each line of code using the Step Into (F8) and Step Over (Shift+F8) commands (or the buttons on the VB toolbar.) The difference between the two commands is that the Step Into command steps through every command, including those in any procedures called by the current procedure. The Step Over command behaves exactly like the Step Into command until a call to a procedure is encountered. Step Over executes calls to procedures as one command (instead of stepping through each line in the called procedure) and then continues stepping.

    The Stop Statement

    When the procedure encounters a Stop statement, it presents the Debug window. The difference between the Stop statement and a breakpoint is that the statement is part of the executable code and is saved with the program. All break points are cleared when the file containing the procedure is closed.

    Watch Expressions

    A watch expression follows the value of a particular variable or expression and displays the value in the Watch pane of the Debug window.

    There are two ways to use a watch expression. The first is to select the variable name, expression or property in the code and select the Tools Add Watch command. This adds the variable to the list of expressions in the Watch pane. As the code executes, the value of the expression changes. It is also possible to set the Watch Type in this dialog. This is useful for instructing VB to break automatically when the value of the expression becomes True or when it changes.

    A second way to use a watch expression is to use the Instant Watch command. By selecting a variable or expression in the code and either pressing the Instant Watch button or selecting the command on the Tools menu, a dialog appears which shows the current value of the expression. Pressing the Add button adds it to the Watch pane.

    The Immediate Pane

    The Immediate pane displays information that results from debugging statements in the code or statements that are typed directly in the Immediate pane.

    Information is displayed in the Immediate pane from within a procedure using the Print method. For example, the following code displays "The value of x is ?" in the Immediate pane:

    Debug.Print "The value of x is " & x

    Or, the print method may be used directly in the Immediate pane by typing:

    Print x

    The question mark (?) is the equivalent of the Print command in the Immediate pane, so the following line produces the same result:

    ? x

    Pressing the Enter key causes the statement to evaluate. The Immediate pane will also accept other Visual Basic commands, even those that change the values of variables and properties or change the behavior of the code.

    Multiple lines of code can be entered on one line using the colon (:) as a separator, which is useful for loops:

    For x=1 to 5 : ? x : Next

    Procedure Call Stack

    The Calls dialog is useful when tracking the operation of code as it executes through a series of procedures. This is especially useful when tracking nested procedures. To view a list of all the nested calls, select the button to the right of the Procedure box.

    If, for example, procedure A called procedure B, which called procedure C, the Call dialog will list procedure C, then B, then A, with the most recently called procedure listed at the top.

    The procedures are added to the list when they are called and removed from the list as they are completed.

    Try This: A Visual Basic Debugging Interface Tour

    Insert a new Module. Display the Debug Window.

    The Immediate Pane

    1. Activate the Immediate pane and type the following:


    2. x = 2 <Enter>
      y = 3 <Enter>
      z = x + y <Enter>
      ? z <Enter.
      The result "5" is displayed in the Immediate pane.
    3. The previous example could have been written as follows:


    4. x = 2 : y = 3 : z = x + y : ? z <Enter>
    5. Type the following:


    6. L = len("The len function") : ? L <Enter>
      The result is 16.
    7. Type the following:


    8. MsgBox "Howdy!"
      Any command that can be entered in the code window can be entered in the Immediate Pane.

    The Watch Pane

    1. Type the following code on a new module sheet:


    2. Sub Main()
      Dim sum as Integer
      sum = Add (3, 6)
      End Sub


    3. Insert a second Module sheet and enter the following code:


    4. Function Add(x, y) as Integer
      add = x + y
      End Function
    5. Run Main. It executes, but the value is not displayed where it can be viewed. Add the following line to Main under the "sum" line:


    6. Debug.Print "Sum: " & sum
    7. Run Main again. Now, open the Debug window and view the contents of the Immediate panel.
    8. Use the Watch pane to display the value of x, y, add and sum during execution. In Module2, select "x" and then click the Instant Watch button and choose Add. Repeat with the remaining variables.

    9. Click on "Sub main()" and press the F8 key (the Step Into command equivalent) the macro in Debug mode. Select the Watch tab in the Debug window.

    10. Step through the macro and view the values returned to the Watch pane.

    Procedure Call Stack

    1. Insert 3 new module sheets.
    2. Enter the following code in Module3:


    3. Sub one()
      two
      End Sub
    4. Enter the following code in Module4:


    5. Sub two()
      three
      End Sub
    6. Enter the following code in Module5:


    7. Sub three()
      one
      End Sub
    8. Select Module3. Click on "Sub one()" and press the F8 key five times. Click on the Procedure Call button. The Calls dialog displays the chain of procedures that have been called but have not finished executing.
    9. Select "GLOBAL.Module3.Sub One()" and press the Show key. The contents of Module3 are displayed.
    Handling Run-time Errors

    As mentioned earlier, run-time errors are errors that occur while the procedure executes and are not syntax related. For example, the procedure tries to open a file that does not exist, the user enters the wrong type of data in a dialog box or the wrong type of sheet is active when the procedure executes. Procedures can be written to anticipate these types of errors and correct the condition, alert the user to the problem or gracefully exit from the procedure.

    VB provides the programmer with three tools for working with run-time errors; the On Error statement, the Err function and the Error function.

    On Error

    The On Error statement has three forms

    On Error GoTo

    The On Error GoTo statement enables an error handling routine and specifies the location of the routine within a procedure. The routine must be located within the procedure which enables the error handling routine and error checking remains active until the procedure completes execution or it is turned off (see details below). The On Error GoTo statement is usually placed at the top of the procedure and then any error which occurs during the procedure directs execution to the routine. A suggested format for the statement is:

    Sub MySub()

    SubLabel:

    On Error GoTo ErrorHandler

    . . .

    Exit Sub

    ErrorHandler:

    . . .

    Resume Next

    End Sub

    Notice that the label "ErrorHandler" appears towards the bottom of the procedure and the name is followed with a colon (:). This tells VB that this is a line label. The line number may also be used but it is not as easy to read the code when numbers are used instead of labels.

    The Exit Sub statement is placed in the line preceding the error handling routine. This prevents the routine from executing in the event that no errors are found. The Resume Next statement instructs VB to return execution to the line immediately following the line that generated the run-time error. The Resume statement could also be followed by a label to be used as a reference for where to resume. In the above example, subsitiuting Resume SubLabel: for Resume Next would cause the macro to continue running at the label’s location.

    On Error Resume Next

    This form of the On Error statement instructs VB to resume execution at the line immediately following the line which generated the error. The programmer should then write error checking into the procedure to respond accordingly.

    On Error GoTo 0

    This statement disables error checking.

    The Err Function

    The Err function returns an integer which represents the most recent error that occurred in the program. For example, when a divide by zero error occurs, the Err function returns 11 or when a file not found error occurs, the value returned to Err is 53. The Err function can be used to determine the type of error that called an error handling routine.

    For a complete list of all the error values, search for "trappable errors" in the VB on-line Help.

    The Error Function

    The Error function returns a message as text which corresponds to a error number. For example, the following line will display a message which shows the error number and the error message of the most recent error:

    MsgBox "The most recent error number is " & Err _

    & ". Its message text is: " & Error(Err)

    Lesson 5 Exercises

    1. Is it possible to add a Watch while in Step Mode? If so, how?
    2. Yes, highlight the variable to watch in the code pane of the Debug window, press the Instant Watch Tool on the Visual Basic toolbar and choose the Add button. Or choose Tools Add Watch.

    3. Write a procedure which will do the following: Prompt the user for a file name. If the file exists, open the file. If the file does not exist, display a custom error message and then ask the user if they wish to try another file or stop the program. Take action as specified.
    4. Sub GetFile()

      Dim goodFile As Boolean

      On Error GoTo errorHandler

      Do

      goodFile = True

      fileName = InputBox(prompt:="Enter a filename")

      If fileName = "" Then Exit Sub

      FileOpen fileName

      If goodFile Then Exit Sub

      Loop

      errorHandler:

      goodFile = False

      Msg = "The file, " & fileName & ", is either already open or not available."

      x = Application.Message(Message:=Msg, Type:=pjYesNo, _

      YesText:="Try Again", NoText:="Exit Procedure")

      If x = True Then Resume Next

      End Sub