Debugging Basics

This section discusses the basics of debugging your application. Debugging is more an art form than a science, and as such you'll need to decide what works best for you. These techniques give you a good understanding of the available tools and how to use them.

The Immediate Window

Use the Immediate window to display the results of statements in your code. Sometimes referred to as the Debug window, its main purpose is to display debugging information. To open the Immediate window, choose View > Immediate Window or press Ctrl+G.

To execute code in the Immediate window, type the statement into it and press the Enter key. To see the statement's return value, precede the statement with a question mark (?), as shown in Figure 2-2.

Figure 2-2. Viewing the Application.Path statement's return value

Figure 2-2. Viewing the Application.Path statement's return value

You typically use the Immediate window for these tasks:

• Testing new code

• Querying and/or changing a variable's value while your application is running

• Querying and/or changing a property value while your application is running

• Calling procedures similarly to calling them in code

• Viewing your program's debugging information while it runs

To can get help on syntax for functions, statements, properties, or methods in the Immediate window, select the keyword, property name, or method name and press F1.

Adding a Watch

Adding a watch lets you observe the value of any valid Visual Basic expression. To create a watch, choose Debug > Add Watch. The dialog box in Figure 2-3 appears.

Figure 2-3. Creating a watch using the Add Watch dialog box

If you have watches already defined in your code, the Watch window appears when the program's execution hits that watch. If a watch expression is out of scope, the Watch window contains no value. To display the Watch window, choose View > Watch Window.

The Call Stack

The Call Stack window, shown in Figure 2-4, lists started procedures that have not completed. This feature is available only in break mode, which is when program execution pauses. When the current procedure's code is executed, VBA adds the procedure to a list of active procedures. VBA also adds each Sub, Function, or Property procedure that the procedure calls. As execution returns to the calling procedure, each procedure is removed from the list. The Immediate window procedures you execute are added to the Call Stack as well. To open the Call Stack window, when in break mode, click View > Call Stack or press Ctrl+L.

Call Stack

_xj

Project, Module. Function

1

Figure 2-4. Viewing unfinished procedures in the Call Stack window

The Locals Window

The Locals window, shown in Figure 2-5, is similar to the Watch window, except that it displays local values—that is, variables declared in the current procedure. To open the Locals window, choose View > Locals Window.

Locals

m

1 -=Read)-i>

Expression 1 Value |TVpe

A

Figure 2-5. Viewing local values in the Locals window Breakpoints

You use breakpoints to stop program execution at a statement in a procedure where you think a problem may exist. Breakpoints are cleared when they are no longer needed. To set a breakpoint, follow these steps:

1. Place the insertion point somewhere on the line of code where you want to stop execution.

2. Choose Debug > Toggle Breakpoint, press F9, or click next to the statement in the margin indicator bar if it's visible.

VBA adds the breakpoint and highlights the line using the breakpoint color defined on the Editor tab in the VBAIDE's Options dialog box.

■ Note Setting a breakpoint on a line that contains several statements separated by colons (:) breaks at the first statement on the line.

To clear a breakpoint, follow these steps:

1. Place the insertion point somewhere on the line of code containing the breakpoint.

2. Choose Debug > Toggle Breakpoint, press F9, or click next to the statement in the margin indicator bar if it's visible.

VBA clears the breakpoint and removes the highlighting.

To clear all the breakpoints in your application, choose Debug > Clear All Breakpoints or press Ctrl+Shift+F9.

Note Breakpoints are not saved when you save your code.

Stepping Through Your Code

You can step through your code, which executes it one line at a time. Using this feature lets you monitor the effects of code on system and application variables.

VBA gives you four methods to step through your code: Step Into, Step Over, Step Out, and Run to Cursor (see Table 2-5).

Table 2-5. Methods for Stepping Through Code

Method_Function_

Step Into Executes your code one statement at a time. To use this method, choose

Debug > Step Into or press F8.

Step Over Executes a procedure as a whole unit, and then returns and steps to the next statement in the current procedure. To use this method, choose Debug > Step Over or press Shift+F8.

Step Out Executes the remaining code of a Sub or Function, and then displays the state ment following the procedure call. This feature is available in break mode only. To use this method, choose Debug > Step Out or press Ctrl+Shift+F8.

Run to Cursor Executes from the current statement in design mode to where you place the cursor. To use this method, click Debug > Run to Cursor or press Ctrl+F8.

The On Error Statements

If you don't use an On Error statement, any run-time error is fatal—that is, an error message appears and execution stops.

■ Note An error-handling routine is a section of code marked by a line label such as HandleError: or a line number.

On Error initiates error handling, which lets the application decide whether an error is fatal. It provides a structured means of controlling how execution will continue for nonfatal errors and stops execution for fatal errors.

Error-handling routines typically rely on the value in the Err object's Number property. The error-handling routine should test or save relevant property values in the Err object before any other error can occur or before the program calls a procedure that might cause an error. The Err object's property values reflect only the most recent error. Err.Description contains the error message associated with Err.Number.

■ Note VBA, VBScript, Visual Basic, and Visual Basic .NET are significantly different from each other in their error-handling features and capabilities.

On Error Resume Next

The On Error Resume Next statement allows execution to continue despite a run-time error. Execution can continue either with the statement right after the statement that caused the run-time error or with the statement right after the most recent call out of the procedure that contains the On Error Resume Next statement. You can place the error-handling routine inline with where the error would occur, rather than transferring control to another location in the procedure:

Dim oLayer As AcadLayer On Error Resume Next

Set oLayer = Application.ActiveDocument.Layers.Add(Name) If Err = 0 Then

Set CreateLayer = oLayer End If

The On Error Resume Next statement becomes inactive when another procedure is called, so use an On Error Resume Next statement in each called routine if you want inline error handling in that routine.

■ Note The On Error Resume Next structure may be preferable to On Error GoTo when handling errors generated during access to other objects. Checking Err after each interaction with an object removes ambiguity about which object the code accessed, which object placed the error code in Err.Number, and which object originally generated the error (specified in Err.Source).

On Error GoTo 0

On Error GoTo 0 disables the current procedure's error handling. It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. Without an On Error GoTo 0 statement, Visual Basic disables error handling when it exits the procedure.

Exit Sub, Exit Function, and Exit Property

To prevent error-handling code from running when no error has occurred, place an Exit Sub, Exit Function, or Exit Property statement immediately before the error-handling routine, as in this example:

Public Function ConnectToAutoCAD(WindowState As AcWindowState) As AcadApplication On Error GoTo HandleError

Exit Function

ExitHere: Exit Function

HandleError:

Resume ExitHere End Function

In this example, the error-handling code follows the Exit Function statement and precedes the End Function statement to separate it from the procedure flow. You can place error-handling code anywhere in a procedure, but you typically place it at the end for easy maintenance.

The Err Object

The Err object contains information about run-time errors. You will use the Err object quite a bit to keep your applications from crashing on the end user at run time. Typically, you'll most frequently use the Err object's Description and Number properties and its Clear method.

The Description Property

The Description property is a string describing the error. Users will appreciate you displaying this property in a MsgBox control instead of crashing the program.

The Number Property

The Number property is the error's number. Some errors give you only a number to use. All of this book's examples list both the Description and Number properties.

To use the Err object, include the following statement in your procedure, which executes if an error should occur:

On Error GoTo HandleError

If an error occurs, execution goes directly to the error handler, as shown in this example:

ExitHere: Exit Sub

HandleError:

MsgBox Error: & Err.Description & ( & Err.Number & ) Resume ExitHere

If an error should happen, this example successfully traps the error and lets your application exit gracefully. Include this construct where the user is likely to make an error. The Resume statement tells Visual Basic where to continue execution after handling the error.

■ Note For a more detailed list of Number property values and their meanings, search for the phrase trappable errors in AutoCAD VBA's online help. Most OLE objects return errors whose numbers are in a unique range; you usually have to convert them to get their descriptions.

The Clear Property

The Clear property clears any error's Err object. The most common use of this property is when VB programmers try to connect or start an instance of AutoCAD, as in this example:

Dim Application As AcadApplication On Error Resume Next

Set Application = GetObject(Class:="AutoCAD.Application")

If Err Then Err.Clear

Set Application = CreateObject(Class:="AutoCAD.Application") If Err Then

MsgBox "Error connecting to AutoCAD", vbCritical, "AutoCAD Fatal Error" Exit Sub End If End If

In this example, the On Error Resume Next statement tells Visual Basic to keep executing code should an error occur. This lets you gracefully handle the error. This example first tries to connect to an already running instance of AutoCAD. If that attempt fails, then the Err object holds the error code. The Err object's Clear method then clears the error. It then tries to start AutoCAD. If that attempt fails, then the application can't continue.

0 0

Post a comment