27
Visual Studio .NET Debugger: D.1 Introduction Two types of errors occur during software development: syntax errors and logic errors. Syntax errors (or compilation errors) occur when program statements violate the grammatical rules of a programming language, such as failure to end a statement with a semicolon. When a compiler detects syntax errors, the compiler terminates without building the application. By contrast, logic errors do not prevent programs from compiling or executing, but rather prevent programs from operating as expected. Syntax errors are easier to fix than are logic errors. Upon detecting a syntax error, the compiler gives the description and line number in the Task List window (Fig. D.1). This information gives the programmer a “clue” as to how to eliminate the error, so the compiler can create the program. However, logic errors often are more subtle and usually do not inform the user exactly where in the program the error occurred. This appendix overviews both types of errors and details Visual Studio .NET’s capabilities for detecting and correcting these logic errors.

Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

Visual Studio .NET Debugger:D.1 Introduction

Two types of errors occur during software development: syntax errors and logic errors.Syntax errors (or compilation errors) occur when program statements violate the grammatical rules of a programming language, such as failure to end a statement with a semicolon. When a compiler detects syntax errors, the compiler terminates without building the application. By contrast, logic errors do not prevent programs from compiling or executing, but rather prevent programs from operating as expected.

Syntax errors are easier to fix than are logic errors. Upon detecting a syntax error, the compiler gives the description and line number in the Task List window (Fig. D.1). This information gives the programmer a “clue” as to how to eliminate the error, so the compiler can create the program. However, logic errors often are more subtle and usually do not inform the user exactly where in the program the error occurred. This appendix overviews both types of errors and details Visual Studio .NET’s capabilities for detecting and correcting these logic errors.

Page 2: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

Testing and Debugging Tip D.1After fixing one error, you may observe that the number of overall errors perceived by the compiler is significantly reduced. 24.0

Testing and Debugging Tip D.2When the compiler reports a syntax error on a particular line, check that line for the syntax error. If the error is not on that line, check the preceding few lines of code for the cause of the syntax error. 24.0

Debugging is the process of finding and correcting logic errors in applications. Logicerrors are more subtle than syntax errors because a program that includes a logic error compiles successfully but does not run as expected. Logic errors often are difficult to debug, because the programmer cannot see the code as it executes. One strategy that novice programmers often use to debug programs is to display program data directly, using message boxes or Console.WriteLine statements. For example, the programmer might print the value of a variable when its value changes to determine whether the variable is assigned the correct value. This approach is cumbersome, because

Page 3: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

programmers must insert a line of code wherever they suspect there might be a problem. Furthermore, once the program has been debugged, the programmer then must remove the extraneous statements, which often can be difficult to distinguish from the original program code.

A debugger is software that allows a programmer to analyze program data and trace the flow of program execution while the application runs. A debugger provides capabilities that allow the programmer to suspend program execution, examine and modify variables, call methods without changing the program code and more. In this appendix, we introduce the Visual Studio .NET debugger and several of its debugging tools. [Note: A program must successfully compile before it can be used in the debugger.]

D.2 Breakpoints

Breakpoints are a simple but effective debugging tool. A breakpoint is a marker that a programmer places in a code listing. When a program reaches a breakpoint, execution pauses— this allows the programmer to examine the state of the program and ensure that it is working as expected. Figure D.2 is a program that outputs the value of ten factorial (10!)1, but contains two logic errors—the first iteration of the loop multiplies x by 10 instead of multiplying x by 9, and the result of the factorial calculation is multiplied by 0 (so the result is always 0). We use this program to demonstrate Visual Studio .NET’s debugging abilities— using its breakpoint capabilities as our first example.

Page 4: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

To set breakpoints in Visual Studio, click the gray area to the left of any line of code or right-click a line of code and select Insert Breakpoint. A solid red circle appears, indicating that the breakpoint has been set (Fig. D.3). The program execution is suspended when it reaches the line containing the breakpoint.

To enable breakpoints and other debugging features, we must compile the program using the debug configuration (Fig. D.4). Select Debug from the configuration toolbar if it is not already selected. Alternatively, select Build > Configuration Manager and change the Active Solution Configuration to Debug.

Page 5: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

Selecting Debug > Start compiles the program and begins debugging. When debugginga console application, the console window appears (Fig. D.5), allowing program interaction (input and output). When the debugger reaches the breakpoint (line 18) program execution is suspended, and the IDE becomes the active window. Programmers may need to switch between the IDE and the console window while debugging programs.Figure D.6 shows the IDE with program execution suspended at the breakpoint. The yellow arrow to the left of the statement

x *= i;

indicates the line at which execution is suspended and that the line contains the next statement to execute. Note that the title bar of the IDE displays [break]—this indicates that the IDE is in break mode (i.e., the debugger is running). Once the program reaches the breakpoint, a programmer can “hover” with the mouse on a variable (in this case x

Page 6: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

or i) in the source code to view the value of that variable in a tooltip as shown in Fig. D.6.

Testing and Debugging Tip D.3Placing a breakpoint after a loop in a program allows the loop to complete without stopping before the breakpoint is reached. 24.0D.3 Examining Data

Visual Studio .NET includes several debugging windows that allow programmers to examine variables and expressions. All the windows are accessible from the Debug > Windows submenu. Some windows are listed only when the IDE is in break mode (also called debug mode). The Watch window, which is available only in break mode (Fig. D.7), allows programmers to examine the values of related groups of variables and expressions. Visual Studio .NET provides a total of four Watch windows.

Page 7: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

Upon first opening, the Watch window will not contain any expressions to evaluate. To examine data, type an expression into the Name field. Most valid C# expressions can be entered in the Name field, including

Page 8: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

expressions that contain method calls. Consult the documentation under “debugger, expressions” for a full description of valid expressions.

Once an expression is entered, its type and value appear in the Value and Type fields.The first expression entered is the variable i, which has a value of 10 (line 12 assigns the value of 10 to variable x, and line 17 assigns the value of x to i). The Watch window also can evaluate more complex arithmetic expressions (e.g, (i + 3) * 5). Thus, the Watch window provides a convenient way to display various types of program data without modifying code.

By entering the variables and expressions that are relevant to a program’s logic error, programmers can trace incorrect values to the source of the error and eliminate it. For example, to debug the program in Fig. D.2, we might enter the expression i * x in theWatch window. When we reach the breakpoint for the first time, the expression has a value 100 instead of 90, which indicates a logic error in our program. This occurs because the loop at lines 17–18 started multiplying x by 10 as opposed to multiplying by 9. We subtract 1 from the initial value that the for loop assigns to i (i.e., change 10 to 9) to correct the error.

If a Name field in the Watch window contains a variable name, the variable’s value can be modified for debugging purposes. To modify a variable’s value, click its value in theValue field and enter a new value. Any modified value appears in red. If an expression is invalid, an error appears in the Value field. For example, Variable ThatDoesNotExist is not an identifier used in the program (fourth line in Fig. D.7).Therefore, Visual Studio .NET issues an error message in the Value field. To remove an expression, select it and press Delete. Visual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the programmer does not specify their contents.

The Locals window displays the name and current value for all the variables that have block scope in the method containing the current statement (indicated by the yellow arrow in Fig. D.6). The Autos window displays the variables and values of the current statement and the previous statement. Variables can be changed in either window by clicking the appropriate Value field and entering a new value. The This window displays data that has class scope for an object. If the program is inside a static method (such as method Main in a console application), the This window is empty.

Page 9: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

A programmer can evaluate expressions line-by-line in the Immediate window (Fig. D.9). To evaluate an expression, a programmer types this expression into the window and presses Enter. For example, when a programmer enters Console.WriteLine(i) and presses Enter, the value of i is output to the console window.

A developer also can use the assignment operator (=) to perform assignments in the Immediate window. Notice that the values for i and x in the Locals window contain these updated values.Testing and Debugging Tip D.4Use the Immediate window to call a method one time. Placing a method call inside theWatch window calls that method every time the program breaks. 24.0

D.4 Program Control

The Visual Studio .NET Debugger give programmers considerable control over the execution of a program. Using breakpoints and program-control commands provided by the debugger, programmers

Page 10: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

conveniently can analyze the execution of code at any point in a program. This is useful when a program contains multiple calls to methods that are known to execute properly.

The Debug toolbar contains buttons that provide convenient access for controlling the debugging process (Fig. D.10). To display the Debug toolbar, select View > Toolbars > Debug. The debug toolbar in Fig. D.10 controls debugger execution. The Restart button executes the program from the beginning, pausing at the beginning of the program to allow the programmer to set breakpoints before the program executes again. The Continue button resumes execution of a suspended program.

The Stop Debugging button ends the debugging session, and the Break All button allows the programmer to suspend an executing program directly (i.e., without explicitly setting breakpoints). After execution suspends, the yellow arrow appears indicating the next statement to be executed.Testing and Debugging Tip D.5When a program is executing, problems such as infinite loops usually can be interrupted by selecting Debug > Break All or by clicking the corresponding button on the toolbar. 24.0

Clicking the Show Next Statement button places the cursor on the same line as the yellow arrow. This command is useful when a programmer needs to return to the current execution point after setting breakpoints in a program that contains many lines of code.

The Step Over button executes the next executable statement and advances the yellow arrow to the following line. If the next line of code contains a method call, the method is executed in its entirety as one step. This button allows the user to execute the program one line at a time without seeing the details of every method that is called. This is useful when a program contains multiple calls to methods that are known to execute properly.

We discuss the Step Into and Step Out buttons in the next section. The Hex button toggles the display format of data. If enabled, Hex displays data in hexadecimal (base 16) format, rather than displaying data in decimal (base 10) format. Experienced programmers often prefer to read values in hexadecimal format—especially large numbers because hexadecimal number representation is more concise and can be converted easily to binary (base 2) form. For more information about the hexadecimal and decimal number formats, see Appendix B, Number Systems.

Page 11: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

The Breakpoints window displays all the breakpoints set for the program (Fig. D.11). A checkbox appears next to each breakpoint, indicating whether the breakpoint is active (checked) or disabled (unchecked). Lines with disabled breakpoints contain an unfilled red circle rather than a solid one (Fig. D.12). The debugger does not pause execution at disabled breakpoints.

Page 12: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

Testing and Debugging Tip D.6Disabled breakpoints allow the programmer to maintain breakpoints in key locations in the program so they can be reactivated when needed. Disabled breakpoints are always visible.24.0

In the Breakpoints window (Fig. D.11), the Condition field displays the condition that must be satisfied to suspend program execution at that breakpoint. The Hit Count field displays the number of times the debugger has stopped at each breakpoint. Double-clicking an item in the Breakpoints window moves the cursor to the line containing that breakpoint.

A programmer can add breakpoints to a program by clicking the New button in the Breakpoints window. This causes a New Breakpoint dialog to display (Fig. D.13). The Function, File, Address and Data tabs allow the programmer to suspend execution at either a method, a line in a particular file, an instruction in memory or when the value of a variable changes. The Hit Count... button (Fig. D.14) can be used to specify when the breakpoint should suspend the program (the default is to always break).

A breakpoint can be set to suspend the program when the hit count reaches a specific number, when the hit count is a multiple of a

Page 13: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

number or is greater than or equal to a specific number. The Visual Studio debugger also allows execution to suspend at a breakpoint depending on the value of an expression. Clicking the Condition… button opens the Breakpoint Condition dialog (Fig. D.15). The Condition checkbox indicates whether breakpoint conditions are enabled. The radio buttons determine how the expression in the text box is evaluated.

The is true radio button pauses execution at the breakpoint whenever the expression is true. The has changed radio button causes program execution to suspend when it first encounters the breakpoint and again each time the expression differs from its previous value when the breakpoint is encountered. When the New Breakpoint dialog has been closed, the Breakpoints window displays the condition and hit count options for the new break point.

Suppose we set x * i != 0 as the condition for the breakpoint in our loop, with the has changed option enabled. (We might choose to do this because the program produces an incorrect output of 0). Program execution suspends when it first reaches the breakpoint and records that the expression has a value of true, because x * i is 100 (or 10 if we fixed the earlier logic error). We continue, and the loop decrements i. While i is between10 and 1, the condition’s value never changes, and execution is not suspended at that breakpoint.

When i is 0, the expression x * i !=0 is false, and execution is suspended.At this point, the programmer identifies the second logic error in our program—the final iteration of the for loop multiplies the result by 0. To return the IDE to design mode, click the Stop Debugging button on the Debug toolbar.

Page 14: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the
Page 15: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

D.5 Additional Method Debugging Capabilities

In programs with many methods, it is often difficult to determine which methods may have been involved in incorrect calculations that resulted in a logic error. To simplify this process, the Visual Studio debugger includes tools for analyzing methods and method calls. We demonstrate some method-debugging tools in the following example (Fig. D.16). The Call Stack window contains the program’s method call stack, which allows the programmer to determine the exact sequence of calls that lead to the current method and to examine calling methods on the stack.

This window allows the programmer to determine the flow of control in the program that resulted in the execution of the current method. For example, a breakpoint is inserted in MyMethod, the call stack in (Fig. D.17) indicates that the program called method Main first, followed by MyMethod.

Page 16: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the
Page 17: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

Double-clicking any line in the Call Stack window displays the next line to be executed in that method. This allows the programmer to determine how the result of each method will affect the calling method’s execution. Visual Studio .NET highlights the line in green and displays the tooltip shown in Fig. D.18. Visual Studio .NET also provides additional program-control buttons for debugging methods.

The Step Over button executes one statement in a method, then pauses program execution at the following line. Using Step Over, if an evaluated statement invokes a method, the method is invoked, and execution stops at the next statement. Using Step Into, if a statement invokes a method, control transfers to the method for line-by-line. The Step Out button finishes executing the current method and returns control to the line that called the method.Testing and Debugging Tip D.7Use Step Out to finish a method that was stepped into accidentally. D.7

Figure D.19 lists each program-control debug feature, its shortcut key and a description.Experienced programmers often prefer using these shortcut keys to access menu commands.

Page 18: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

Programmers can use the Immediate window, discussed in Section D.3 for testing method arguments passed to a method (Fig. D.20). Testing the arguments helps determine if a method is functioning properly.

Page 19: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

D.6 Additional Class Debugging Capabilities

In most sophisticated C# programs, a large portion of program data is contained in objects. For these purposes, Visual Studio includes class debugging features, which allow programmers to determine the current state of objects used in a program. We demonstrate some class debugging features using the code presented in Fig. D.21. To examine an instance of class DebugEntry, we place a breakpoint at line 43, as shown in Fig. D.22. [Note: A C# file may contain multiple classes, as is the case with this example

Page 20: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the
Page 21: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

To assist class debugging, Visual Studio .NET allows the programmer to expand and view all data members and properties of a class, including private members. In any of the three windows (i.e., Watch, Locals, Autos and This), a class that has data members is displayed with a

Page 22: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

plus (+) (Fig. D.23). When a programmer clicks the plus box, all the object’s data members and their values display. If a member references an object, the object’s data members also can be listed by clicking the object’s plus box.

Many logic errors are the result of incorrect array calculations. To simplify the identification of such errors, the debugger includes the ability to display all the values in an array. Figure D.24 displays the contents of the list array. The object at index 0 is and int array, which is expanded to show its contents. Index 1 contains a DebugClass object— expanded to show the object’s private data members, as well as a public property.

Index 2 contains a Random object, defined in the Framework Class Library (FCL).The Visual Studio debugger contains several other debugging windows, including Threads, Modules, Memory, Disassembly and Registers. These windows are used by experienced programmers to debug large, complex projects—consult the Visual Studio .NET documentation for more details on these features.

In this appendix we demonstrated several techniques for debugging programs, methods and classes. The Visual Studio .NET debugger is a powerful tool, which allows programmers to build more robust, fault-tolerant programs.

SUMMARY• Debugging is the process of finding logic errors in applications.• Syntax errors (or compilation errors) occur when program statements violate the grammaticalrules of a programming language. These errors are caught by the compiler.• Logic errors are more subtle than syntax errors. They occur when a program compiles successfully,but does not run as expected.• Debuggers can suspend a program at any point, which allows programmers to examine and setvariables and call methods.• A breakpoint is a marker set at a line of code. When a program reaches a breakpoint, execution issuspended. The programmer then can examine the state of the program and ensure that the programis working properly.

Page 23: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

• To enable the debugging features, the program must be compiled using the debug configuration.• To set breakpoints, click the gray area to the left of any line of code. Alternatively, right-click aline of code and select Insert Breakpoint.• The Watch window allows the programmer to examine variable values and expressions. To examinedata, type a valid Visual Basic expression, such as a variable name, into the Name field.Once the expression has been entered, its type and value appear in the Type and Value fields.

Page 24: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

• Variables in the Watch window can be modified by the user for testing purposes. To modify avariable’s value, click the Value field and enter a new value.• The Locals window displays the name and current value for all the local variables or objects inthe current scope.• The Autos window displays the variables and objects used in the previous statement and the currentstatement (indicated by the yellow arrow).• To evaluate an expression in the Immediate window, simply type the expression into the windowand press Enter.• The Continue button resumes execution of a suspended program.• The Stop Debugging button ends the debugging session.• The Break All button allows the programmer to place an executing program in break mode.• The Show Next Statement button places the cursor on the same line as the yellow arrow thatindicates the next statement to execute.• The Step Over button executes the next executable line of code and advances the yellow arrowto the following executable line in the program. If the line of code contains a method call, the methodis executed in its entirety as one step.• The Hex button toggles the display format of data. If enabled, Hex displays data in a hexadecimal(base 16) form, rather than decimal (base 10) form.• The Breakpoints window displays all the breakpoints currently set for a program.• Disabled breakpoints allow the programmer to maintain breakpoints in key locations in the programso they can be used again when needed.• The Call Stack window contains the program’s method call stack, which allows the programmerto determine the exact sequence of calls that led to the current method and to examine callingmethods on the stack.• The Step Over button executes one statement in a method, then pauses program execution.• The Step Into button executes next statement. If the statement contains a method call, controltransfers to the method for line-by-line debugging. If the statement does not contain a method call,Step Into behaves like Step Over.• The Step Out finishes executing the method and returns control to the line that called the method.

Page 25: Visual Studio - Philadelphia University€¦ · Web viewVisual Studio also provides the Locals, Autos and This windows (Fig. D.8), which are similar to the Watch window, except the

• The Immediate window is useful for testing arguments passed to a method. This helps determineif a method is functioning properly.• Visual Studio .NET includes class debugging features which allow the programmer to determinethe current state of any objects used in a program.• To assist class debugging, Visual Studio .NET allows the programmer to expand and view all datamembers variables and properties of an object, including those declared private.