Exercises 7 – Debugging

advertisement
Introduction to C# and the Visual Studio IDE
Exercises 7 –Debugging
Introduction
A bug is some sort of error in the code which can prevent the program from running properly.
When you write a substantial program always assume it contains bugs. When you discover a
bug you may or may not know how your code has caused it. Debugging is about finding
these causes. Visual Studio has a variety if debugging tools, which are discussed in the first
part of the chapter. The second part of this chapter looks at how your code can trap run-time
errors, for which the normal process of debugging is not relevant.
Types of error
There are three types of error:

Syntax error

Run-time error

Logic or Semantic error
Syntax errors are those that appear while you write your code. Visual Basic checks your code
as you type and alerts you if you make a mistake, such as misspelling a word or using a
language element improperly. Syntax errors are the most common type of errors. You can fix
them easily in the coding environment as soon as they occur.
Run-time errors are those that appear only after you compile and run your code. These
involve code that may appear to be correct in that it has no syntax errors, but that will not
execute. The topic of exception handling is concerned with dealing with these situations in a
satisfactory way.
Logic errors are those that appear once the application is in use. They most often take the
form of unwanted or unexpected results in response to user actions. For example, a mistyped
key or other outside influence might cause your application to stop working within expected
parameters, or altogether. Logic errors are generally the hardest type to fix, since it is not
always clear where they originate.
The topic of debugging in this chapter is not concerned with syntax or run-time errors but with
tracking down logic errors.
The three program modes
At any time a given program is in one of three modes – design mode, run mode or break
mode. Every program you have written has used the design and run modes. If your program
produces a run-time error it automatically invokes break mode. When in break mode you can
hover the cursor over any variable and see its current value. Some of the features covered in
the first part of the chapter only work in break mode
Stepping through code
The Debug toolbar has three options, and the Debug menu two of the three options for stepping through
code – executing it one line at a time. Both the Step Into and Step Over options will run the current line
of code.
Using Breakpoints
A breakpoint is a place in the code where the program will temporarily stop. You can set as
many of these as you like. When the program stops at a breakpoint you examine the
contents of variables and expressions in the Watch window or in the Immediate window.
The next two programs show how to use the Watch and Immediate windows.
1
Watches
A watch allows you to see the value of a variable or expression as the program runs. As you
step through the code this value is displayed in the Watch window. You can only add a watch
when the program is in break mode.
Program 7.1 Breakpoints, setting Watches and stepping through code
Specification: Demonstrate how to set a breakpoint, set watches on variables and
expressions, and how to step through code.
1. Open a new project. Place a list box on the form and name it lstDisplay. Set its Dock
property to fill.
2. Type the following into the form’s Load event handler
int number;
number = 2;
for(int counter = 1; counter <=10; counter++)
{
lstDisplay.Items.Add("2 to the power " +
counter + " is " + number);
number*= 2;
}
3. Run the program and confirm that it keeps doubling the current number as shown below:
4. To set a watch on a variable we must be in break mode. One way of getting into this
mode is to set a breakpoint somewhere in the program. Click in the margin to the left of
number *= 2; as shown in the figure below. The line of code will be highlighted in brown
and a circle will appear next to it in the bar.
2
5. Run the program. Execution will stop at the breakpoint, which will be highlighted in
yellow. To set a watch on the on the variable number, highlight it and right-click and then
select Add Watch. The Watch window will appear at the bottom of the screen (with the
title Watch1 since you can use up to four watch windows). The current value of number
is shown as 0, because the breakpoint line of code, which sets it to 2, has not yet been
executed.
6. Now we are going to execute the code line by line and see what happens in the Watch
window. You can step through the code either by using the F10 key, clicking the Step
Into icon on the Debug toolbar or selecting Step Into from the Debug menu. Press the
F10 key once. The start of the for loop is now highlighted and the value of of number is
now 2 in the Watch window.
7. Press the F10 key five more times and the value of number will be doubled to 4. Keep
pressing this key until its value becomes 512.
8. Select Debug/Stop Debugging or click Stop Debugging on the Debug toolbar to stop
the program. Remove the breakpoint by clicking on the circle in the Margin Indicator bar.
End of program 7.1
The Immediate Window
The Immediate window lets you do a variety of things such as look at and change the
contents of variables. As with the Watch window these can only be done in break mode.
Program 7.2 The Immediate Window
Specification: Demonstrate the use of the Immediate Window.
This is a simple program that asks the user to enter a product’s unit price and the quantity
brought. If the total price exceeds £200 there is a 10% discount. It outputs the total price
after the discount.
1. Open a new project. Place two text boxes txtPrice and txtQuantity, two labels and a
button btnImmediate on the form as in the figure below.
2. Type the following code for the button’s Click event.
int quantity = 0;
double price = 0, discount = 0, totalPrice;
price = Convert.ToDouble(txtPrice.Text);
quantity = Convert.ToInt32(txtQuantity.Text);
if ((price * quantity) > 200)
3
{
discount = price * quantity * 0.1;
}
totalPrice = price * quantity - discount;
MessageBox.Show("Total price is: " + totalPrice.ToString("c"));
3. Run the program to check that it works.
4. Comment out the two lines that get input from the user. Place a breakpoint on the line
with the if condition.
5. Run the program so that it stops at the breakpoint. Select Debug/Windows/Immediate
from the main menu to get the Immediate window.
6. In the Immediate window set the value of Price and Quantity as shown in the figure
below. Press Enter after each line.
7. Press the F10 key three times to step through the code to the end of the IF statement. In
the Immediate window display the value of the variable discount by typing in ?discount;
and pressing Enter. The result is shown in the figure below. The discount is 30.0 (10%
of 50 x 6).
8. Remove the breakpoint and stop debugging the program.
End of program 7.2
The Output Window.
You can debug a program directly from the code using the Output window. In the first program
if we had written a Console.WriteLine() immediately after number *= 2
Console.WriteLine("The value of number is: " + number);
The Output window would display the value of number each time it is executed. You will have
seen this window many times before when your program has finished running and you are
brought back to design mode. If it is not visible you can get it by selecting View/Other
Windows/Output Window.
4
Summary of key concepts

A bug is an error in a program. Debugging is the process of finding and removing
errors

The Debug toolbar and Debug menu provide aids in tracking logic errors.

To step through code is to execute it line by line.

A watch on a variable allows you to see how its value changes during a program.
The Watch Window displays watches.

A breakpoint is a place in the code where the program temporarily stops.

Console.WriteLine<variable identifier> in your code displays the contents of a given
variable in the Output Window.
5
Download