## Visual Basic in 12 Easy Lessons vel24.htm

- What You'll Learn
- The Debugging Routine
- The Debugger
- Entering Break Mode
- Using the Immediate Window
- Homework
  - General Knowledge
  - Find the Bug

#
Lesson 12, Unit 24

##
Debugging For Perfection

###
What You'll Learn

- The debugging routine
- The debugger
- Entering break mode
- Using the Immediate window

This unit finishes the book by taking a break from the usual teaching of controls and code. As you write more and more programs, you'll have more and more success at improving your Visual Basic skills. The problem is that your program errors will increase as well. No matter how careful, almost every programmer introduces errors along with working code. Those errors, known as bugs, are sometimes extremely difficult to find.

Visual Basic contains several debugging tools that help you hunt, find, and correct the bugs that will appear. Visual Basic actually makes finding bugs fun. Well, perhaps you won't use the term fun, but the debugging tools that Visual Basic provides certainly makes locating those errors easier than finding bugs from programming languages that preceded Visual Basic.

###
The Debugging Routine

Concept: Several kinds of errors can occur. Some errors are easy to find and others are not so easy to find. Visual Basic's debugging tools help you zero in on some of the more difficult kinds of program errors that can creep into your code.

> > Definition: A debugger is the integrated tool that helps you find program bugs.

As described in Unit 1, there are two general categories of errors that you'll often run across as you use Visual Basic. The debugger can help you locate and fix these errors. You will find both syntax errors and logic errors.

A syntax error is the easiest kind of error to find. A syntax error often occurs because you misspell a command, function name, or method. A syntax error can also appear because you rearrange the grammar of a loop such as a For loop with a Step option that appears before the loop's To keyword.

As you write your program, Visual Basic will spot syntax errors for you. If you set the Options Environment Syntax Checking option to Yes, Visual Basic actually checks for syntax errors every time you press Enter at the end of any code line that contains an error. Figure 24.1 shows how Visual Basic displays a message box that warns the user of the error.

Figure 24.1. The programmer just typed a syntax error and needs to fix the problem.

When you run across a syntax error message box, press Enter to get rid of the message box and fix the problem. Usually, you'll immediately see the misspelled word and correct the error. If you can't locate the error right away, or if you want to come back to the problem later, Visual Basic will allow you to continue writing the rest of the program without displaying the error message again unless you change the same line and fail to correct the problem.

> > Note: As you can see from Figure 24.1, Visual Basic doesn't always call the error a syntax error but you'll know from the context of the error message that the statement's syntax (grammar or spelling) is wrong.

If you set the Options Environment Syntax Checking option to No, Visual Basic will ignore all syntax errors until you run the program. At runtime, Visual Basic will display the syntax error message boxes as Visual Basic runs across them.

The second kind of error you'll run across is a logic error. Logic errors are more difficult to find. Logic errors aren't errors of grammar or spelling, but are errors in action.

Logic errors appear when your program seems to understand everything you typed but produces incorrect results. For example, suppose that you wrote a program that printed paychecks and, every so often, the program made a calculation error and doubled the amount of withholding for all employees who had been with the company more than ten years. If you were running the program and printing the checks, you would probably not notice the errors. You would notice the errors, however, when the employees began pounding on your office door.

Sometimes, logic errors don't appear until people begin using the program. You'll get the syntax errors out of a program right away because Visual Basic helps you find them with message boxes. People are the hunters and gatherers of logic errors. When you realize that one of your programs has a problem with a calculation, loop, or a procedure, you must return to the Code window and find the problem. In large programs, those logic errors can be difficult to trace.

Logic errors can occur because you forgot to initialize a variable properly, you didn't loop through enough table or list control values, or you reversed data types when you defined variables. Although logic errors are often hard to locate, Visual Basic's integrated debugger, described in the rest of this unit, helps you find logic errors.

Review: There are two general categories of errors: syntax errors and logic errors. Visual Basic finds all syntax errors in your program. The logic errors require work on your part. The debugger, described next, helps you hunt down offending logic errors.

###
The Debugger

Concept: The Debug menu produces a list of all of Visual Basic's debugging commands. Using the debugging commands, you'll be able to stop a program before the execution of any line of code, look at variable and control values, and single step through the code starting at any line.

Figure 24.2 shows the Debug menu. Visual Basic's debugging tools are extremely powerful and allow you to execute programs using one of several methods that enable you to analyze various parts of the code.

Figure 24.2. The debugging tools are available from the Debug command on the menu bar.

> > Definition: Visual Basic enters the break mode when you halt a program during execution.

These menu options are all available during the break mode. These are the three modes that a Visual Basic program can be in:

- Design mode
- Runtime mode
- Break mode

Visual Basic tells you which mode is current by displaying the words design, run, or break in Visual Basic's title bar at the top of your Visual Basic screen. When you develop the program, the program is in the design mode; when you or the user runs a program, the program is in runtime mode; and when you halt a program to use the debugger to analyze program problems, the program enters the break mode.

This unit concerns itself with the break mode. While in break mode, your program retains all variable and control values. Therefore, you can halt the program at any time and look at data values from any line of the code. By comparing the values with what you expect the values to contain, you can find where problems are taking place.

Review: Of Visual Basic's three modes, you'll be using the break mode to debug programs. When a program enters the break mode, the program halts at any line in the program's execution but retains all variable and control values assigned to that point.

###
Entering Break Mode

Concept: There are several ways to enter the break mode. The most common way is to set a breakpoint. You also can halt a program during the program's execution by intercepting the program's execution with Ctrl+Break or by selecting Break from the Run menu at runtime.

You'll always enter the break mode from the runtime mode. Only after you begin a program's execution will the break mode be available, because only at runtime are the variables and controls initialized with values. Here are the ways that you can move from the runtime mode to the break mode:

- Press Ctrl+Break during the program's execution at the place where you want to enter the break mode. Stopping on one particular line of code is virtually impossible when using Ctrl+Break.
- Select Run Break from the menu bar.
- Click the Break toolbar button (the button with the hand icon).
- In design mode or during a break mode, set a breakpoint on a particular line at which you want the execution to halt. By setting a breakpoint, you can specify the exact line of code where Visual Basic is to enter the break mode.
- The debug menu's Add Watch dialog box enables you to specify a break expression that Visual Basic monitors and uses to halt the program's execution when the expression becomes true.
- If a runtime error occurs, such as a division by zero that is an undefined math operation, Visual Basic enters the break mode on the offending line. Sometimes, this kind of error is called a runtime error and fits within the logic error category.

The most accurate and common way to enter the break mode is by setting a breakpoint. To set a breakpoint, find the line where you want execution to halt at a breakpoint, and set a breakpoint at that particular line of code. The following steps walk you through setting a breakpoint:

1. Load the CHECK2.MAK project that comes with this book.
2. Press F7 to open the Code window. Visual Basic opens the code to the Form_Load() event procedure.
3. Find the following line of code in Form_Load():
   lblPoem = lblPoem & "If you ever hear differently,"
4. Move the mouse cursor to the line and click the mouse button. The text cursor appears at the mouse click's location.
5. Select Debug Toggle Breakpoint to set a breakpoint. You'll see from the menu command that F9 is the access key for this command. Also, clicking the toolbar's hand icon would also place a breakpoint on this line of code. Figure 24.3 shows how your code window should appear. Visual Basic changes the color of the line to let you know that a breakpoint will take place on that line during the program's execution.
   You can turn off a breakpoint by selecting the Debug Toggle Breakpoint (or pressing F9) once again. You can set as many breakpoints as you need throughout a program. Leave the breakpoint in place for now. By setting the breakpoint, you're requesting that Visual Basic halt the program and enter break mode when execution reaches this line of code. Close the Code window and run the program by pressing F5.

Figure 24.3. Visual Basic highlights all breakpoints.

As soon as you press F5 to run the program, Visual Basic executes the program. At least, Visual Basic executes the code down to the first breakpoint. As soon as Visual Basic reaches the breakpoint line, Visual Basic enters the break mode before executing the breakpoint line. You can verify the break mode by reading Visual Basic's title bar and seeing the word (break) at the top of the screen.

The CHECK2.MAK application is the program that concatenated and assigned a poem into a label's caption. The Form_Load() procedure builds the concatenated poem. The breakpoint that you set occurs in the middle of the poem-building code. Only two values are initialized at the breakpoint. The string variable Newline contains a carriage return and line feed sequence, and the control named lblPoem contains the poem's text.

At the breakpoint, the lblPoem label contains the first two lines of the poem. Remember that all controls have default properties, and the Caption property is the default property for the label. Therefore, in building the poem, the code doesn't specify that the poem's text is to enter the Caption property of the label. As you'll see, whenever you specify only the label's name, Visual Basic assumes that you want to assign or display the Caption property.

Follow these steps to see what kinds of things you can do at a breakpoint:

1. By dragging the mouse, highlight either mention of the lblPoem control on the breakpoint's line.
2. Click the toolbar button with the eyeglass icon. The eyeglass toolbar button produces the Instant Watch dialog box (which is also available from the Debug menu). Visual Basic displays the first line stored in the lblPoem's Caption property, as shown in Figure 24.4.
   At first, you may be disappointed that the Instant Watch dialog box doesn't show both lines of the label's Caption property contents. Keep in mind, though, that a label might contain a caption that is several thousand characters long. Visual Basic is able to show you only the characters up to the carriage return and line feed characters at the end of the caption's first line.
3. Click the Instant Watch dialog box's Cancel command button to close the dialog box. Visual Basic returns to the Code window's breakpoint.
4. Usually, the programmer will single step through a few lines of code after reaching a breakpoint. To step through the code one line at a time, you can choose Debug Single Step, press F8, or click the single footstep icon on the toolbar. As you single step though the code, Visual Basic highlights the next line of execution. At any point during the single-step process, you can examine variables and controls with the Instant Watch dialog box.

Figure 24.4. Displaying the label's value.

Eventually, the Form_Load() procedure ends and the form appears on the screen. If you were to click one of the option buttons, Visual Basic would execute that option button's event procedure and simultaneously open the Code window once again so that you could continue the single step process.

Suppose that a variable contains an incorrect value but you're not exactly sure where the error is occurring. You could set a breakpoint at every line of code that changes that variable. When you run the program, you'll look at the contents of that variable before and after each breakpoint's line of execution. If the first breakpoint seems to initialize the variable properly, you don't have to single step through the code until the next breakpoint is reached. Instead of single stepping, you can select Run Continue or press F5 to return the execution to its normal runtime (and real time) mode. When Visual Basic reaches the next breakpoint, the code halts at that next breakpoint and you can continue to examine the variable.

Either from the Debug menu or from the Instant Watch dialog box, you can request the Add Watch dialog box. The Add Watch dialog box is shown in Figure 24.5. The Add Watch dialog box allows you to type any expression in the Expression text box.

Figure 24.5. Set up expressions that Visual Basic watches for in the Add Watch dialog box.

The Add Watch dialog box is useful for data errors that you can't seem to locate in the code. Rather than break at every line that uses of the data value, you can add a variable or expression to the Add Watch dialog box, and Visual Basic will halt execution when that variable changes, when the expression that you enter in the Add Watch dialog box becomes true, or when Visual Basic changes the value of the expression (the Watch Type frame at the bottom of the Add Watch dialog box determines how you want to set up the watch).

For example, suppose that a variable is to maintain a count of customers, but somewhere in your code a negative value appears in the variable. If you added a watch expression such as CustCnt < 0 to the Add Watch dialog box's Expression prompt, and clicked the Break when Expression is True option button, you could then run the program and Visual Basic would enter the break mode at the exact line that caused the variable to become negative.

The toolbar buttons with the double footstep icon works almost like the single-step icon except that Visual Basic executes the breakpoint's current procedure in a single-step mode but executes all procedures called by the single-step procedure in their entirety.

Terminate your current debug session by selecting Run End. Visual Basic returns to the design mode.

Review: The breakpoints and watch dialog boxes that you can request while debugging your code give you tremendous power in analyzing variables and watching for specific results. You can look at the contents of variables and controls to make sure that data is being initialized the way you expect. Also, the Add Watch dialog box enables you to set up expressions that Visual Basic watches for during the program's execution. If the values of those expressions ever become true or change, Visual Basic will halt the code at that line and allow you to analyze values using the Instant Watch dialog box.

###
Using the Immediate Window

Concept: The Immediate window enables you to look at and change variables and controls during the execution of a program.

At any breakpoint, you can select Window Debug (Ctrl+B) to request the Debug window. The Debug window is a special window in which you can directly type Visual Basic commands, and view and change variables and control values during a program's execution.

For printing, you can apply the Print method (see Unit 21) to view variables and controls. When you use Print in the Debug window, Visual Basic sends the output to the Debug window and not to the Printer object, as you saw in Unit 21. For example, suppose that you set a breakpoint during the poem's concatenation, as described in the previous section, and you pressed Ctrl+B to open the Debug window. The Debug window recognizes simple commands and methods such as Print and assignment statements.

Figure 24.6 shows what happens if you print the value of the lblPoem. Unlike the Instant Watch dialog box, the Debug window displays the entire multiple line value of the label. You can resize and move the Debug window. Although they must use the Print command instead of simply clicking a variable or control, many users prefer to display values from the Debug window instead of from the Instant Watch dialog box because the Debug window displays the entire value and contains a vertical scroll bar so that they can scroll through the values printed in the window.

Figure 24.6. In the Debug window, you can print values of variables and controls.

> > Use the Debug Window Inside Your Code: The Debug window's scrolling and resizing features are sometimes so handy that some Visual Basic programmers prefer to send messages to the Debug window at runtime rather than use the Instant Watch dialog box. For example, if you want to see the value of certain arguments when called procedures execute, you can add the Print commands at the top of those procedures that send the argument values to the Debug window automatically as the program executes. Once you get the bugs out of the program, you can remove the Print commands so that the Debug window stays closed.
> > To print to the Debug window, preface the Print method with the Debug object. The following command, executed anywhere from an application's Code window, prints the values of two variables with appropriate titles in the Debug window:
> > Debug.Print "Age:"; ageVal, "Weight:"; weightVal
> > All the Print method's options, including semicolons, commas, Tab(), and the Spc() functions, work inside the Debug window just as they did for the Printer object described in Unit 21. Be careful to specify the Debug object before the Print method, however. If you omit Debug, Visual Basic prints the output directly on the form itself!

The Debug window recognizes assignments that you make to variables and controls. For example, suppose that you know that a certain variable wasn't initialized properly earlier in the execution, but you still want to finish the program's execution. If you need to, you can assign that variable a new value directly within the Debug window using the assignment statement. When you resume the program's execution, either in single-step or in runtime mode, the variable, from that point in the program, will contain the value that you assigned to it.

Review: The Debug window gives you more control over the display of variables and controls. The Debug window is resizable and provides you with a scroll bar so that you can see the entire contents of variables and controls as well as keep a running and scrollable tally of those values as you debug the program's execution. The Debug window gives you the ability to assign values to variables and controls as well. In the middle of a program's execution, you can enter the break mode and change the values of anything. When you subsequently resume the program's execution, the program will use those values that you assigned in the Debug window.

###
Homework

####
General Knowledge

1. What are the two major classifications of errors that a program can contain?
2. Which error would describe spelling and grammar errors?
3. What is a debugger?
4. How can you request that Visual Basic check for syntax errors as you type a program into Visual Basic's Code window?
5. True or false: Visual Basic displays a message box when a syntax error appears.
6. True or false: Visual Basic displays a message box when a logic error appears.
7. Which kind of error, syntax or logic, is the most difficult to find?
8. What three modes can a program be in?
9. Which mode is Visual Basic in when you write the program and place items on the form?
10. How can you tell which mode a program is currently in?
11. Which mode is perfect for displaying and changing variables?
12. Name two ways to enter the break mode.
13. What is a breakpoint?
14. How can you set a breakpoint?
15. How do you know that a breakpoint is set when you look through the Code window?
16. What happens when Visual Basic encounters a breakpoint during the execution of a program?
17. What is meant by single stepping through a program?
18. What is the difference between the toolbar button with the single footprint and the double footprint?
19. What is the difference between the Instant Watch and the Add Watch dialog boxes?
20. Which kind of watch is most useful for displaying variables at a program's breakpoint?
21. Which window enables you to view and change Visual Basic variables and controls at runtime?
22. Which command enables you to display data values in the Debug window?
23. Which command enables you to assign new values to variables and controls at runtime?

####
Find the Bug

Jennifer wants to send several values to the Debug window so that she can keep a scrollable list of variable values as she runs a program. Here are some of the statements that Jenny is trying to use to print in the Debug window:
Print lblTitle.Caption
Print x, y, z
Print CompName
Even though Jennifer opens her Debug window during the program's execution, the window is blank. Instead of going to the Debug window, Jennifer's Print methods seem to be appearing on the form itself. Help Jennifer with her problem.