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:
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:
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:
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
The Watch Pane
Procedure Call Stack
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 labels 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)
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.
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