Home > Articles > Programming > Windows Programming

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
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
27      ' initialization phase
28      total = 0 ' set total to zero before adding grades to it
29      gradeCounter = 0 ' prepare to loop
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
38      ' termination phase
39     If gradeCounter <> 0 Then
40         average = total / gradesListBox.Items.Count ' calculate average
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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020