Using C s Debugging Tools

   

Using C#'s Debugging Tools

C# includes a number of debugging tools to help you track down and eliminate bugs . In this section, you'll learn how to use break points, the Command window, and the Output window ”three tools that form the foundation of any debugging arsenal.

Working with Break Points

graphics/newterm.gif

The same way an exception halts the execution of a method, you can deliberately stop execution at any statement of code by creating a break point. When C# encounters a break point while executing code, execution is halted at the break statement, prior to it being executed. Break points enable you to query or change the value of variables at a specific instance in time, and they let you step through code execution one line at a time.

You're going to create a break point to help troubleshoot the exception in your MessageBox.Show() statement.

Adding a break point is simple. Just click in the gray area to the left of the statement at which you want to break code execution. When you do so, C# displays a red circle, denoting a break point at that statement (see Figure 16.4). To clear a break point, click the red circle.

Figure 16.4. Break points give you control over code execution.

graphics/16fig04.jpg


graphics/bookpencil.gif

Break points are saved with the project. This makes it much easier to suspend a debugging session; you don't have to reset all your break points each time you open the project.

Set a new break point on the statement shown in Figure 16.4 (the statement where lngAnswer is set). Do this by clicking in the gray area to the left of the statement. After you've set the break point, press F5 to run the program. Again, click the button. When C# encounters the break point, code execution is halted and the procedure with the break point is shown. In addition, the cursor is conveniently placed at the statement with the current break point. Notice the yellow arrow overlaying the red circle of the break point (see Figure 16.5). This yellow arrow marks the next statement to be executed. It just so happens that the statement has a break point, so the yellow arrow appears over the red circle (the yellow arrow won't always be over a red circle, but it will always appear in the gray area aligned with the next statement to execute).

Figure 16.5. A yellow arrow denotes the next statement to be executed.

graphics/16fig05.jpg


When code execution is halted at a break point, you can do a number of things. See Table 16.1 for a list of the most common actions. For now, press F5 to continue program execution. Again, you get the Format exception. Click Break to access the code procedure with the error.

Table 16.1. Actions That Can Be Taken at a Break Point
Action Keystroke Description
Continue Code Execution F5 Continues execution at the current break statement.
Step Into F11 Executes the statement at the break point and then stops at the next statement. If the current statement is a function call, F11 enters the function and stops at the first statement in the function.
Step Over F10 Executes the statement at the break point and then stops at the next statement. If the current statement is a function call, the function is run in its entirety; then execution stops at the statement following the function call.
Step Out Shift+F11 Runs all the statements in the current procedure and halts execution at the statement following the one that called the current procedure.

Using the Command Window

Break points themselves aren't usually sufficient to debug a procedure. In addition to break points, you'll often use the Command window to debug code. The Command window is a Visual Studio IDE window that generally appears only when your project is in Run mode. If the Command window isn't displayed, press Ctrl+Alt+A to display it now (or use the Other Views submenu of the View menu). Using the Command window, you can type in code statements that C# executes immediately. You'll use the Command window now to debug our problem statement example.

Type the following statement into the Command window and press Enter:

 ? txtInput.Text 

Although not intuitive, the ? character has been used in programming for many years as a shortcut for the word "print." The statement that you entered simply prints the contents of the Text property of the text box.

Notice how the command window displays "" on the line below the statement you entered. This indicates that the text box contains an empty string (also called a zero-length string ). The statement throwing the exception is attempting to use the long.Parse() method to convert the contents of the text box to a Long. The long.Parse() method expects data to be passed to it, yet the text box has no data (the Text property is empty). Consequently, a Format exception occurs.

graphics/bookpencil.gif

Generally, when you receive a Format exception, you should look at any variables or properties being referenced to ensure that the data they contain is appropriate data for the statement. Often, you'll find that the code is trying to perform an operation that is inappropriate for the data being supplied.

You can do a number of things to prevent this error. The most obvious is to ensure that the text box contains a value before attempting to use the long.Parse() method. You'll do this now. C# doesn't allow you to modify code when in break mode, so choose Stop Debugging from the Debug menu before continuing.

Add the following statement to your method, right above the statement that throws the exception (the one with the break point):

 if (txtInput.Text == "") return; 

Press F5 to run the project once more, and then click the button. This time, C# won't throw an exception, and it won't halt execution at your break point; the test you just created causes code execution to leave the procedure before the statement with the break point is reached.

Type your name into the text box and click the button again. Now that the text box is no longer empty, execution passes the statement with the exit test and stops at the break point. Press F5 to continue executing the code, and again you'll receive an exception. Click Break to enter Break mode, and type the following into the Command window (be sure to press Enter when done):

 ? txtInput.Text 

The Command window prints your name.

Well, you eliminated the problem of not supplying any data to the long.Parse() method, but something else is wrong. Press F5 to continue executing the code and take a closer look at the exception text. The last statement in the text says Input string was not in a correct format . It apparently still doesn't like what's being passed to the long.Parse() method. By now, it may have occurred to you that no logical way exists to convert alphanumeric text to a number; long.Parse() needs a number to work with. You can easily test this by entering a number into the text box. Do this now by clicking Break, choosing Stop Debugging from the Debug menu, and pressing F5 to run the project. Enter a number into the text box and click the button. Code execution again stops at the break point. Press F11 to execute the statement. No errors this time! Press F5 to continue execution and C# will display the message box (finally). Click OK to dismiss the message box and then close the form to stop the project.

graphics/bulb.gif

You can use the Command window to change the value of a variable in addition to printing the value.

Because the long.Parse() method expects a number, yet the text box contains no intrinsic way to force numeric input, you have to accommodate this situation in your code. You will learn how to deal with exceptions later on in this chapter using a catch statement.

Using the Output Window

The Output window (see Figure 16.6) is used by C# to display various status messages and build errors. The most useful feature of the Output window, for general use, is the capability to send data to it from a running application. This is especially handy when debugging applications.

Figure 16.6. The Output window displays a lot of useful information ”if you know what you're looking for.

graphics/16fig06.gof


You've already used the Output window in previous hours, but you might not have seriously considered its application as related to debugging. As you can see from Figure 16.6, some data sent to the Output window by C# isn't that intuitive ”in fact, you can ignore much of what is automatically sent to the Output window. What you'll want to use the Output window for is printing data for debugging (as you have done and will do throughout this book). Therefore, it's no coincidence that printing to the Output window is accomplished via the Debug object.

To print data to the Output window, use the WriteLine() method of the Debug object, like this:

 Debug.WriteLine("Results = " + lngResults); 

The Debug object is a member of the System.Diagnostics namespace. Therefore, to define the scope for Debug.WriteLine statements, you will need to add using System.Diagnostics to the header section of your class (along with the other using statements C# creates automatically.

graphics/bookpencil.gif

If you do not add using System.Diagnostics to the top of your code file, you can still access Debug.WriteLine() by writing out the full expression: System.Diagnostics.Debug.WriteLine().

Whatever you place within the parentheses of the WriteLine() method is what is printed to the Output window. Note that you can print literal text and numbers , variables, or expressions. WriteLine() is most useful in cases where you want to know the value of a variable, but you don't want to halt code execution using a break point. For instance, suppose you have a number of statements that manipulate a variable. You can sprinkle WriteLine() statements into the code to print the variable's contents at strategic points. When you do this, you'll want to print some text along with the variable's value so that the output makes sense to you. For example:

 Debug.WriteLine("Results of area calculation = " + sngArea); 

You can also use WriteLine() to create checkpoints in your code, like this:

 Debug.WriteLine("Passed Checkpoint 1"); // Execute statement here Debug.WriteLine("Passed Checkpoint 4"); // Execute another statement here Debug.WriteLine("Passed Checkpoint 3"); 

Many creative uses exist for the Output window. Just remember that the Output window isn't available to a compiled component; calls to the Debug object are ignored by the compiler when creating distributable components .


   
Top


Sams Teach Yourself C# in 24 Hours
Sams Teach Yourself Visual Basic 2010 in 24 Hours Complete Starter Kit (Sams Teach Yourself -- Hours)
ISBN: 0672331136
EAN: 2147483647
Year: 2002
Pages: 253
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net