Lesson 1: Using the Debugging Tools

Lesson 1: Using the Debugging Tools

Programming errors are inevitable. Even very experienced programmers occasionally introduce errors, also known as bugs, while writing code. Debugging is the process of locating and fixing these errors. In this lesson, you will learn about the kinds of errors you are likely to encounter and the tools available to isolate and correct these errors.

After this lesson, you will be able to

  • Describe the common types of errors

  • Explain what Break mode is and how to set breakpoints

  • Describe how to step through code

  • Describe some of the debugging windows that are available and explain how to use them

Estimated lesson time: 45 minutes

Types of Errors

There are three basic types of errors you might encounter when writing code. Syntax errors represent code that cannot be understood by the compiler. Run-time errors are errors that occur when an attempt is made to perform an operation that is impossible to carry out. Logical errors are errors that result when code compiles and executes correctly, but returns an unexpected result. In this section, we will examine each error type in turn.

Syntax Errors

A syntax error occurs when the compiler cannot compile the code it is given. For example, a syntax error occurs when keywords are typed incorrectly, punctuation is omitted, or an incorrect construct is parsed. The following example demonstrates two syntax errors:

Visual Basic .NET

Public Sub SyntaxError() System.Windows.Forms.MessageBoxShow("Where's the error?")

Visual C#

public void SyntaxError() { System.Windows.Forms.MessageBoxShow("Where's the error?");

First, a period is missing between MessageBox and Show, creating an unrecognizable command for the compiler. Second, the closing construct for the method is missing (End Sub in Microsoft Visual Basic .NET and } in Microsoft Visual C#). Both errors will create a condition that the compiler cannot interpret.

You can easily identify syntax errors with Visual Studio .NET. Whenever you build your project, syntax errors are detected automatically and underscored in the code. Detected errors are also added to the Task List window, shown in Figure 5.1.

figure 5-1 the task list window

Figure 5-1. The Task List window

Double-click any error in the Task List window, and the cursor will highlight that error in the code window. Frequently, this action provides sufficient information to correct the error. However, if further information is required, you can obtain help on the highlighted item by pressing F1.

Visual Basic .NET performs syntax checking when code is typed. Syntax errors are immediately underlined and added to the Task List window. It is unnecessary to build the project to identify syntax errors.. Visual C# also performs automatic syntax checking when code is typed, but the level of error detection is less sophisticated.

To identify and correct syntax errors

  1. Build the project. Syntax errors will be detected and added to the Task List window. If you are working in Visual Basic .NET, syntax errors will be added to the Task List window.

  2. Double-click an error in the Task List window. The error will be highlighted in the code editor.

  3. Correct the error. If necessary, you can obtain help by pressing F1.

Run-Time Errors

Run-time errors occur when the application attempts to perform an operation that is not allowed. This includes operations that are impossible to carry out, such as division by zero, and operations that are not allowed, as in the case of security exceptions. When a run-time error occurs, an exception describing the error is thrown. Exceptions are special classes that are used to communicate error states between different parts of the application. You can write code to handle exceptions so that they do not halt execution of your application. Handling exceptions is covered in greater detail in Lesson 4 of this chapter.

Logical Errors

Logical errors occur when the application compiles and executes correctly, but does not produce the expected results. These can be the most difficult type of errors to track down, because there might not be any indication as to the source of the error. Logical errors can result from something as innocuous as a misplaced decimal point. For example:

Visual Basic .NET

Public Function CalculateSalary(ByVal HourlyRate As Single) As Single Dim YearlySalary As Single YearlySalary = HourlyRate * 52 * 400 Return YearlySalary End Function

Visual C#

public float CalculateSalary(float HourlyRate) { float YearlySalary; YearlySalary = HourlyRate * 52 * 400; return YearlySalary; }

The method in the example takes a value for an hourly wage and calculates a yearly salary by multiplying the hourly wage by the number of weeks in the year and hours in a week. An error occurs because the value is multiplied by 400 instead of 40 hours per week. This method will compile and execute correctly, but inappropriate results will be reported. You can detect logical errors by feeding test data into your application and analyzing the results. Testing is covered in Lesson 3 of this chapter. To identify the source of logical errors in code, it is often necessary to examine the code line-by-line. This can be done in Break mode.

Break Mode

Break mode allows you to halt program execution and execute code one line at a time. While in Break mode, you can use the debugging tools to examine the values of application variables and properties. Visual Studio .NET enters Break mode under any of the following circumstances:

  • You choose Step Into, Step Over, or Step Out from the Debug menu or toolbar.

  • Execution reaches a line that contains an enabled breakpoint.

  • Execution reaches a Stop statement.

  • An unhandled exception is thrown.

Table 5.1 summarizes the features found on the Debug menu.

Table 5-1. Debug Menu Items

Menu Item

Shortcut Key

Description

Windows

Opens a submenu of debugging windows. These windows are discussed in detail later in this lesson.

Start/Continue

F5

Runs the application in Debug mode. If the application is in Break mode, this option continues program execution.

Break All

Ctrl+Alt+Break

Causes program execution to halt and enter Break mode at the current program line. Choose Continue to resume execution.

Stop Debugging

Shift+F5

Stops the debugger and returns Visual Studio .NET to Design mode.

Detach All

Detaches the debugger from all processes it is debugging. This closes the debugger but does not halt program execution.

Restart

Ctrl+Shift+F5

Terminates and restarts application execution.

Apply Code Changes

Used only with C/C++ programming. Cannot be used with Visual Basic .NET or Visual C#.

Processes

Displays the Processes window.

Exceptions

Ctrl+Alt+E

Displays the Exceptions window.

Step Into

F11

Runs the next executable line of code. If the next line calls a method, Step Into stops at the beginning of that method.

Step Over

F10

Runs the next executable line of code. If the next line calls a method, Step Over executes that method and stops at the next line within the current method.

Step Out

Shift+F11

Executes the remainder of the current method and breaks at the next executable line of code in the calling method.

QuickWatch

Ctrl+Alt+Q

Displays the QuickWatch window.

New Breakpoint

Ctrl+B

Displays the New Breakpoint window.

Clear All Breakpoints

Ctrl+Shift+F9

Removes all breakpoints from the application.

Disable All Breakpoints

Disables all breakpoints, but does not delete them.

Additionally, some debugging functions can be accessed by right-clicking on an element in the code window and choosing a function from the pop-up menu. Some of these functions are summarized in Table 5.2.

Table 5-2. Code Window Pop-Up Menu Debugging Functions

Menu Item

Description

Insert Breakpoint

Inserts a breakpoint at the selected line.

New Breakpoint

Displays the New Breakpoint window.

This menu item is identical to the Debug menu item of the same name.

Add Watch

Adds the selected expression to the Watch window.

QuickWatch

Displays the QuickWatch window. This menu item is identical to the Debug menu item of the same name.

Show Next Statement

Highlights the next statement to be executed.

Run To Cursor

Runs program execution to the selected line.

Set Next Statement

Designates the selected line as the next line of code to be executed. The selected line must be in the current procedure.

Some of the more commonly used debugging features are discussed in the following sections.

Using Step Into

You can use Step Into to examine your program execution line-by-line. When you choose Step Into to step through your code, the application executes the current line, and then returns to Break mode. If the current line is a method call, the debugger advances to the first line of that method. After the line has been executed, you can examine the state of your application using the various debugging windows.

To use Step Into

Select Step Into from the Debug menu or from the Debug toolbar, or press F11.

Using Step Over

You can use Step Over in much the same way you use Step Into. Step Over behaves identically to Step Into, except when a function call is encountered; in this case, Step Over executes the entire function call and advances to the next line. You should use Step Over when you want to stay at the same level in your code and there is no need to analyze any nested method calls.

To use Step Over

Select Step Over from the Debug menu or from the Debug toolbar, or press F10.

Using Step Out

Step Out allows you to execute the remainder of code in the current procedure. If the current procedure was called from another method, execution advances to the statement following the line that called that procedure.

To use Step Out

Select Step Out from the Debug menu or from the Debug toolbar, or press Shift+F11.

Using Run To Cursor

The Run To Cursor option allows you to choose a line of code and execute all of the code in the application up to that line. You can use this option to skip over blocks of code that do not need to be executed line-by-line. For example, you might use Run To Cursor to step over a large loop.

To use Run To Cursor

In the code editor, place the cursor on the line you want to run to. This line must be an executable line of code. Right-click and choose Run To Cursor.

Using Set Next Statement

You can use Set Next Statement to skip over sections of code. Set Next Statement allows you to set the next statement within the current method to be executed, skipping over any intermediate code. Unlike Run To Cursor, the code that is skipped is not executed. You can use Set Next Statement to skip sections of code that contain known bugs. You also can use Set Next Statement to choose a line of code that has already been executed.

To use Set Next Statement

  1. In the code editor, place the cursor on the line you want to designate as the next executed line. This line must be an executable line of code within the current procedure.

  2. Right-click, and choose Set Next Statement. You can then use Step Into to execute the line.

Examining Variable Values

You can examine the value of program variables while in Break mode by hovering the mouse pointer over the variable in code. The current value of the variable will be displayed in a pop-up box. This technique provides a quick and easy way to determine the current value of a variable. For more detailed information about a variable s state, you should use the Watch, Autos, or Locals windows, which are further discussed in this lesson.

Setting Breakpoints

You can designate lines of code or conditions that will cause the application to break in the debugger. These are called breakpoints. You can use breakpoints to set lines of code or conditions that will halt program execution. There are four types of breakpoints:

  • Function breakpoints.

    Cause the application to enter Break mode when a specified location within a function is reached.

  • File breakpoints.

    Cause the application to enter Break mode when a specified location within a file is reached.

  • Address breakpoints.

    Cause the application to enter Break mode when a specified memory address is accessed.

  • Data breakpoints.

    Cause the application to enter Break mode when the value of a variable changes. This option is not available when programming in Visual Basic .NET and Visual C#.

To set a function breakpoint

Function breakpoints are the breakpoints that are most commonly used. You can set a function breakpoint in one of three different ways:

  • By clicking the gray bar to the left of the code window at the desired line. This will insert a breakpoint at the specified line.

  • By right-clicking the desired line of code and choosing Insert Breakpoint from the pop-up window.

  • By choosing New Breakpoint from the Debug menu or by right-clicking in the code editor and choosing New Breakpoint from the pop-up menu. You can then add a new breakpoint by setting the appropriate parameters in the New Breakpoint window.

The Breakpoints Window

The Breakpoints window allows you to manage all of your breakpoints in a single window, as shown in Figure 5.2. You can display the Breakpoints window by choosing Windows from the Debug menu, then selecting Breakpoints.

figure 5-2 the breakpoints window.

Figure 5-2. The Breakpoints window.

The Breakpoints window lists all of the breakpoints in your project, where the breakpoint is located, and any conditions attached to the breakpoint. You can choose additional columns of information about your breakpoints from the Columns drop-down menu. You can disable a breakpoint by clearing the check box next to it. Also, the button in the top-left corner of the window allows you to create a new breakpoint, delete a breakpoint, or clear or disable all breakpoints.

Clearing and Disabling Breakpoints

When a breakpoint is no longer needed, you can remove it. Or, if you want to retain a breakpoint, but do not need it at that moment, you can disable it. You can use the Breakpoints window to manage your breakpoints. You also can remove or disable a breakpoint in the code editor.

To remove a breakpoint in the code editor

Click the breakpoint in the gray bar to the left of the code editor. This will remove the breakpoint.

To disable a breakpoint in the code editor

Right-click the breakpoint in the code editor, and choose Disable Breakpoint. This will disable the breakpoint.

Breakpoint Properties and Setting Breakpoint Conditions

You can view a breakpoint s properties by right-clicking the breakpoint in either the code editor (Visual Basic .NET only) or the Breakpoints window and choosing Properties. This causes the Breakpoint Properties window to be displayed. The Breakpoint Properties window has three tabs: Function, File, and Address, and each tab shows the breakpoint expressed as that particular type. Thus, you might set a Function breakpoint in the code editor, but that breakpoint also can be expressed as a File breakpoint or an Address breakpoint, and that information can be found in the Breakpoint Properties window.

In addition to the three tabs, the Breakpoint Properties window has two buttons: the Conditions button and the Hit Count button. Pressing the Condition button displays the Breakpoint Condition window, which allows you to designate an expression that causes the breakpoint to be active only if the expression is true or if the expression changes. When testing whether an expression is true, the expression that you designate can be any valid expression that resolves to a Boolean value. For example, you could set a breakpoint in code, choose the Is True radio button, and designate the condition myBoolean = False (Visual Basic .NET) or myBoolean == false (Visual C#). This would cause the breakpoint to be active only when the variable named myBoolean is false. You also can use the negation operator to get the same effect, for example, Not myBoolean (Visual Basic .NET) or !myBoolean (Visual C#).

Another method is to designate a variable or expression that when changed will cause execution to break. In this case, the expression you designate needs only to be a valid expression. For example you could choose the has changed radio button and designate myVariable or any other variable name. You can also designate more complex expressions, such as x + y , which causes the breakpoint to be enabled only when the value of x + y changes.

Pressing the Hit Count button in the New Breakpoint dialog box opens the Breakpoint Hit Count window, where you can set the breakpoint to be active only when it has been hit a predetermined number of times, a multiple of a predetermined number of times, or a number of times that is equal to or greater than a predetermined number. For example, if you set the hit count condition to break only when the hit count is a multiple of 10, program execution will break every tenth time the breakpoint is encountered.

NOTE
The breakpoint must be active to be counted. Thus, if you have a breakpoint that has conditions of x = true and break when the hit count is a multiple of 10 , program execution will break only when this breakpoint is encountered for the tenth time.

Using the Debugging Windows

Visual Studio provides several tools, or windows, to monitor program execution. Some, such as the Output window and the Command window, are available in Design mode. Others, such as the Locals window, are visible only while debugging.

The Output Window

The Output window displays all of the command-line output from the application as the application is compiled and executed. This output includes notifications from the application that assemblies have loaded, as well as output from Debug and Trace statements. When debugging your application, you primarily will use the Output window to receive Debug notifications. Using the Debug class is discussed in Lesson 2 of this chapter. The Output window is usually visible by default, but if it is not visible, you can display it by choosing View, then Other Windows, and selecting Output.

The Locals, Autos, and Watch Windows

The Locals, Autos, and Watch windows are windows that allow you to monitor the status of program variables while the application is being debugged. Additionally, these windows allow you to edit the values of variables while debugging. This can be useful when testing how procedures respond to different input.

The Locals Window

When the program is running in Debug mode, the Locals window allows you to monitor the values of all the variables in the current procedure. The Locals window contains three columns of information: a Name column that displays the name of the variable, a Value column that displays the variable s value, and a Type column that displays the variable s type. Complex types such as classes or structures are displayed in a tree view that can be expanded to reveal the values of their members. As program execution shifts from method to method, the variables displayed within the Locals window also shift so that only the local variables are displayed. You can alter the value of a variable in the Locals window by selecting its value under the Value column and typing a new value. Note that only strings and numeric values can be changed in this manner. You cannot set a class or structure variable to refer to another instance of that class or structure, although you can change variable values within the class or structure. When a value is changed, it appears as red in the Value column.

To display the Locals window

While debugging your application, choose Debug then Windows, and select Locals.

The Autos Window

The Autos window is like an abbreviated form of the Locals window. The Autos window displays the same data columns as the Locals window, but only displays the variables in the current line and the previous line (Visual C#) or the variables in the current line and three lines on either side of the current line (Visual Basic .NET). You can alter the variable value in the Autos window, just as you would in the Locals window.

To display the Autos window

While debugging your application, choose Debug, then Windows, and select Autos.

The Watch Window

The Watch window is where you designate a variable to track. Variables added to the Watch window remain in the window even when they are out of scope. Like the Locals and Autos windows, the Watch window displays the variable s Name, Value, and Type, and you can alter the running values of noncomplex variables by typing a new value into the Value column. Visual Studio .NET provides four separate Watch windows for designating multiple sets of watch variables.

You can quickly evaluate a variable by using the QuickWatch dialog box, which can be displayed by right-clicking a variable and choosing QuickWatch. The QuickWatch dialog box shows you the Name, Value, and Type of a single variable, and gives you the option of adding it to the Watch window. You also can use the QuickWatch dialog box to edit the variable value by typing a new value in the Value column.

To display the Watch window

While debugging your application, choose the Debug menu, then Windows, and select Watch1, Watch2, Watch3, or Watch4.

To display the QuickWatch dialog box

In the code editor, right-click a variable and choose QuickWatch from the pop-up menu.

To add a variable to the Watch window

You can add a variable to the Watch window in one of the following ways:

  • Select an empty row in the Watch window and type the variable name.

  • In the code editor, right-click on a variable and choose Add Watch from the pop-up menu.

  • Using the mouse, highlight and drag a variable from the code editor, the Autos window, or the Locals window.

  • In the QuickWatch dialog box, press the Add Watch button.

Immediate Mode in the Command Window

The Immediate mode of the Command window is used to execute procedures, evaluate expressions, or change variable values during debugging. You can display the Command window in Immediate mode by selecting Debug, then Windows, and then Immediate.

In Immediate mode, the command window can evaluate any valid statements or method calls but cannot accept data declarations. If the application is in Break mode, you can enter a statement or method call in the Command window, as you would in the code editor. When you press Enter, Visual Studio switches to run time and executes the statement. The application returns to Break mode after execution of the statement or method call is complete.

You can print variable values directly in the Command window when the application is in Break mode the question mark (?) lets you print the value of an expression or variable in the Command window. The following example multiplies the current values of x and y and prints them to the Command window:

? X*Y

Note that the syntax is the same for both Visual Basic .NET and Visual C#. In the case of Visual C#, no semicolon is required to terminate the line. You can use the same syntax to print the value of any property currently in scope. For example, the code

? TextBox1.Text

prints the current value of the Text property of TextBox1.

The assignment operator can be used to assign a new value to an existing variable. The following code example sets the value of x to 5:

X = 5

Note that the variable must be already declared.

To display the Command window

From the View menu, choose Other Windows, then Command Window. You can also display the Command window in Immediate mode by selecting Debug, then Windows, and then Immediate.

Other Windows

Several additional windows allow you to obtain information on your program s execution or manage Break mode while you are debugging. Table 5.3 summarizes the other windows that are available from the Debug menu.

Table 5-3. Other Windows Available from the Debug Menu

Window

Summary

Running Documents

Displays a list of documents currently loaded into the process you are running.

Me (Visual Basic .NET) / This (Visual C#)

Displays the data members of the object associated with the current method.

Call Stack

Displays the names of functions on the call stack, parameter types, and parameter values.

Threads

Allows for examination and control of threads in the program you are debugging.

Modules

Lists the modules (DLL or EXE files) used by your program.

Memory

Displays the raw values stored in memory. You can use a Memory window to view large buffers, strings, and other data that do not display well in the Locals, Autos, or Watch windows.

Disassembly

Shows assembly code corresponding to the instructions created by the compiler.

Registers

Displays register contents. You can keep the Registers window open as you step through your program to see register values change as code executes.

Lesson Summary

  • The three types of errors you might encounter while writing your program are:

    • Syntax errors, which represent syntax the compiler cannot interpret.

    • Run-time errors, which occur when an impossible operation is attempted.

    • Logical errors, which compile and execute correctly, but return unexpected results.

  • You can use Break mode to examine your code line-by-line to identify and correct errors. Visual Studio .NET provides several options for stepping through code, including:

    • Step Into.

      To step through each line of code as it executes, including calls to other functions

    • Step Over.

      To step through each line of code as it executes, but step over calls to other functions

    • Step Out.

      To execute the remainder of code in the current function and stop at the next line in the function that called it, if applicable

    • Run To Cursor.

      To designate a line with the cursor and execute all the code leading up to that line

    • Set Next Statement.

      To set the next statement to be executed, skipping and not executing any intermediate lines

  • Breakpoints, used for debugging, are designated lines of code where execution halts and the application enters Break mode. Breakpoints can have conditions attached that determine whether the application will break or not. The Breakpoints window is where you manage, create, disable, or clear breakpoints.

  • Visual Studio .NET provides several tools for evaluating your program. The Locals, Autos, and Watch windows allow you to observe program variables while the application is running. The Command window allows you to execute code and print variable and property values to the window. Additional windows allow you to observe a variety of data regarding your application.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

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