Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

4.12 Using the Debugger: Locating a Logic Error

You'll now begin learning about the Visual Basic 2010 Express tools that can help you find and correct logic errors (also called bugs). Such errors do not prevent a program from compiling successfully, but can cause a running program to produce incorrect results. Visual Studio includes a tool called a debugger that can be used to monitor the execution of your programs so you can locate and remove logic errors. Aprogram must successfully compile before it can be used in the debugger. Some of the debugger's features include:

  • suspending program execution so you can "step" through the program one statement at a time
  • examining and setting variable values
  • watching the values of variables and expressions
  • viewing the order in which methods are called

To illustrate some of the debugger's capabilities, let's use a modified version of the class-average program from Fig. 4.12. In the modified version (located in the Debugging folder with this chapter's examples), the condition in line 32 uses the <= rather than the < operator. This bug causes the loop in calculateAverageButton_Click to execute its statements one extra time. The program fails at line 33 when it attempts to access a grade that does not exist. The modified event handler is shown in Fig. 4.16.

Fig 4.16. Modified calculateAverageButton_Click event handler that contains a logic error.

18   ' calculate the class average based on the grades in gradesListBox
19  Private Sub calculateAverageButton_Click(ByVal sender As System.Object,
20   ByVal e As System.EventArgs) Handles calculateAverageButton.Click
21
22     Dim total As Integer ' sum of grades entered by user
23     Dim gradeCounter As Integer ' counter for grades
24     Dim grade As Integer ' grade input by user
25     Dim average As Double ' average of grades
26
27      ' initialization phase
28      total = 0 ' set total to zero before adding grades to it
29      gradeCounter = 0 ' prepare to loop
30
31      ' processing phase
32     Do While gradeCounter <= gradesListBox.Items.Count
33         grade = gradesListBox.Items(gradeCounter) ' get next grade
34         total += grade ' add grade to total
35         gradeCounter += 1 ' add 1 to gradeCounter
36     Loop
37
38      ' termination phase
39     If gradeCounter <> 0 Then
40         average = total / gradesListBox.Items.Count ' calculate average
41
42         ' display total and average (with two digits of precision)
43         classAverageLabel.Text = "Total of the " & gradeCounter &
44           " grade(s) is " & total & vbCrLf & "Class average is " &
45            String.Format("{0:F}", average)
46     Else
47         classAverageLabel.Text = "No grades were entered"
48     End If
49  End Sub ' calculateAverageButton_Click

The Off-By-One Logic Error

Execute this program with Debug > Start Debugging (or by pressing F5 or the toolbar button arrow.jpg). Enter several grades and press the Calculate Class Average Button. The program does not display the class average. Rather, you get a dialog in the IDE showing a runtime error known as an ArgumentOutOfRangeException (Fig. 4.17). This indicates that the argument in parentheses (gradeCounter) is out of range. As you'll soon see, gradeCounter's value is one higher than the index of the last grade in the gradesListBox, so the program attempts to get a value that does not exist. This logic error—commonly known as an off-by-one error—is frequently caused by using the incorrect relational operator in a loop's condition. The debugger highlights the line of code (line 33) that caused the problem.

Fig. 4.17

Fig. 4.17 IDE showing the line of code that caused an Argument Out Of Range Exception.

In the following steps, you'll use various debugger commands to examine the values of the variables used in the calculateAverageButton_Click event handler and to study the flow of control in the Do While...Loop repetition statement. This will help us locate and correct the logic error.

4.12.1 Breakpoints and Running the Program

Breakpoints are special markers that you can set at any executable line of code. You cannot place them on comments or whitespace. When a running program reaches a breakpoint, execution pauses, allowing you to examine the values of variables to help determine whether logic errors exist. For example, you can examine the value of a variable that stores a calculation's result to determine whether the calculation was performed correctly. You can also examine the value of an expression. Once the debugger pauses program execution, you can use various debugger commands to execute the program one statement at a time—this is called "single stepping" or simply "stepping." We'll examine the code in the averageButton_Click event handler. Before proceeding, if you ran the program to cause the logic error, stop the debugger by selecting Debug > Stop Debugging.

Inserting a Breakpoint

To insert a breakpoint, left click in the margin indicator bar (the gray margin at the left of the code window in Fig. 4.18) next to line 28, or right click in line 28 and select Breakpoint > Insert Breakpoint. Additionally, you can click a line of code then press F9 to toggle a breakpoint on and off for that line of code. You may set as many breakpoints as you like. A solid circle appears in the margin indicator bar where you clicked and the entire code statement is highlighted, indicating that a breakpoint has been set.

Fig. 4.18

Fig. 4.18 Breakpoint set at line 28.

Running the Program in Debug Mode

After setting breakpoints in the code editor, select Debug >Start Debugging (or press the F5 key) to rebuild the program and begin the debugging process. Enter the grades 100, 97 and 88, then press the Calculate Class Average button. When the debugger reaches line 28 (the line that contains the breakpoint), it suspends execution and enters break mode (Fig. 4.19). At this point, the IDE becomes the active window. The yellow arrow to the left of line 28—called the instruction pointer—indicates that this line contains the next statement to execute. The IDE also highlights the line as well to emphasize the line that is about to execute.

Fig. 4.19

Fig. 4.19 Program execution suspended at the first breakpoint.

4.12.2 Quick Info Box

In break mode, you can place the mouse cursor over any variable and its value will be displayed in a Quick Info box (Fig. 4.20). This can help you spot logic errors.

Fig. 4.20

Fig. 4.20 Quick Info box displays value of variable gradeCounter.

4.12.3 Locals Window

While in break mode, you can also explore the values of a method's local variables using the debugger's Locals window (Fig. 4.21). To view the Locals window, select Debug > Windows > Locals. Recall that all variables in Visual Basic get initialized, so even though lines 28–29 have not executed yet, variables total and gradeCounter currently have the value 0 (the default for Integer variables). In Fig. 4.21, we call out only the variables declared in lines 22–25.

Fig. 4.21

Fig. 4.21 Locals window showing the values of the variables in the event-handler method .

4.12.4 Using the Step Over Command to Execute Statements

You'll now execute the program one statement at a time using the debugger's Step Over command. You can access this command by selecting Debug >StepOver, by pressing Shift + F8 or by pressing the Step Over command's toolbar icon (transfer.jpg). Do this twice now. The instruction pointer arrow now points to the Do While...Loop statement's first line. If you position the mouse over the word Count in gradesListBox.Items.Count (Fig. 4.22), you can see in the Quick Info window that the number of items in the ListBox is 3. Similarly, you can place the mouse over variable gradeCounter to see that its value is currently 0.

Fig. 4.22

Fig. 4.22 Stepping over a statement in the calculateAverageButton_Click method calculateAverageButton_Click.

At this point in the program's execution, the user cannot add more items to the ListBox because we've disabled the TextBox and Button that allow the user to enter a grade, so gradesListBox.Items.Count will remain as 3. Thus, the loop should execute the statements at lines 33–35 a total of three times to process the three grades.

First Iteration of the Loop

Since gradeCounter's value is less than or equal to 3, the condition in line 32 is true. Thus, when you use the Step Over command again, the instruction pointer moves to line 33 in the loop's body. Now use the Step Over command to execute line 33. The first item in the ListBox (100) is assigned to variable grade, which you can see in the Quick Info box and in the Locals window. Whenever a variable's value is modified as a result of the last statement to execute, the Locals window highlights that value in red.

Now, Step Over lines 34 and 35 to add the grade to the total and to add 1 to the gradeCounter. The instruction pointer is now aimed at line 36. When you use the Step Over command now, the instruction pointer moves back to the top of the loop so the condition can be tested again.

Second Iteration of the Loop

Variable gradeCounter's value is now 1, so the condition is still true, thus the loop's body will execute again. Use the Step Over command five times to step through this iteration of the loop, which adds the grade 97 to the total, increments gradeCounter to 2 and positions the instruction counter at the top of the loop.

Third Iteration of the Loop

Variable gradeCounter's value is now 2, so the condition is still true, thus the loop's body will execute again so we can process the last grade. Use the Step Over command five times to step through this iteration of the loop, which adds the grade 88 to the total, increments gradeCounter to 3 and positions the instruction counter at the top of the loop.

Fourth Iteration of the Loop

At this point, we've processed all three grades and the loop should terminate. However, gradeCounter's value is 3, which is less than or equal to 3. The condition is still true—even though we are done processing the three grades. Thus, the loop will attempt to process another grade, even though one does not exist. This is the logic error. When you Step Over line 33 again, you get the error shown in Fig. 4.17.

Fixing the Logic Error

Stepping through the program in this manner enables you to see that the loop's body executes four times when it should only execute three times. So we can focus on the loop's condition as the source of the logic error, because the condition determines when the loop should stop executing. To correct the error, you can stop the debugger by selecting Debug > Stop Debugging, then edit the code by changing the <= operator in line 32 to a < operator. You can then test the program again to ensure that it is executing properly. To execute the program without the breakpoints, you can:

  1. Disable each breakpoint by right clicking in the line of code with the breakpoint and selecting Breakpoint > Disable Breakpoint, then run the program;
  2. Remove each breakpoint by right clicking the breakpoint and selecting Delete Breakpoint, then run the program; or
  3. Execute the program without debugging by pressing Ctrl + F5.
  • + Share This
  • 🔖 Save To Your Account