Home

Errors and Exceptions: Options on Debugging

 
  

Debugging and Separate Files

 

Introduction

 

In the previous sections, we dealt with one or a few procedure in only one file. As you know already, a program can use many files, some files come from the .NET Framework you create the others as you judge them necessary for your project. As a result, when debugging, you can consider files that are linked at one time or another. The process of debugging is primarily the same. You just have to keep in mind that you are dealing with different files. This has some consequences on the results you see.

ApplicationApplication: Debugging With a Class

  1. Start Microsoft Visual Basic
  2. To start a new project, on the main menu, click File -> New Project...
  3. In the middle list, click Console Application
  4. Change the Name to WattsALoan2
  5. Click OK
  6. On the main menu, click Project -> WattsALoan2 Properties
  7. Click the arrow of the Application Type box and select Windows Forms Application
  8. To create a new class, in the Solution Explorer, right-click WattsALoan2 -> Add -> Class...
  9. In the middle list, make sure Class is selected.
    Change the Name to Customer and click Add
  10. Change document as follows:
    Public Class Customer
        Public FullName As String
        Public PhoneNumber As String
    
        Public Sub New(Optional ByVal Name As String = "John Doe",
                       Optional ByVal Phone As String = "000-000-0000")
            FullName = Name
            PhoneNumber = Phone
        End Sub
    End Class
  11. To create a new class, in the Class View, right-click WattsALoan2 -> Add -> Class...
  12. Change the Name to Employee and press Enter
  13. In the empty document, type the following:
    Public Class Employee
        Public EmployeeNumber As Long
        Public FirstName As String
        Public LastName As String
        Public Title As String
    
        Public Sub New(Optional ByVal EmplNbr As Long = 0,
                        Optional ByVal FName As String = "Unknown",
                        Optional ByVal LName As String = " Not Specified",
                        Optional ByVal Position As String = "Loan Specialist")
            EmployeeNumber = EmplNbr
            FirstName = FName
            LastName = LName
            Title = position
        End Sub
    
        Public Function GetEmployeeName() As String
            Return LastName + ", " + FirstName
        End Function
    End Class
  14. To add a new class to the project, on the main menu, click Project -> Add Class...
  15. Change the Name to LoanInformation
  16. Click Add
  17. In the empty document, type the following:
    Public Class LoanInformation
        Public Principal As Double
        Public InterestRate As Double
        Public Period As Double
        Public InterestAmount As Double
        Public FutureValue As Double
    End Class
  18. In the Solution Explorer, right-click Module1.vb and click Rename
  19. Type LoanEvaluation.vb and press Enter twice
  20. In the empty document, type the following:
    Module LoanEvaluation
        Private Clerk As Employee
        Private Client As Customer
        Private Loan As LoanInformation
    
        Private Sub IdentifyEmployee()
            MsgBox("Enter the following pieces of information " +
                              "about the employee who prepared this loan.")
            Clerk.EmployeeNumber = CLng(InputBox("Employee #: ",
                                      "Watts A Loan?", "000000"))
            Clerk.FirstName = InputBox("First Name:")
            Clerk.LastName = InputBox("Last Name:")
            Clerk.Title = InputBox("Title:")
        End Sub
    
        Private Sub IdentifyCustomer()
            MsgBox("Enter the following pieces of information " +
                              "about the customer for whom this loan was prepared.")
            Client.FullName = InputBox("Customer Name:")
            Client.PhoneNumber = InputBox("Phone Number:")
        End Sub
    
        Private Sub GetLoanValues()
            MsgBox("Enter the following pieces of information " +
                              "about the values used for the loan.")
            Loan.Principal = CDbl(InputBox("Enter the principal:"))
            Loan.InterestRate = CDbl(InputBox("Enter the interest rate:")) / 100
            Loan.Period = CDbl(InputBox("Enter the number of months:")) / 12
        End Sub
    
        Public Sub Show()
            loan.InterestAmount = loan.Principal * loan.InterestRate * loan.Period
            loan.FutureValue = loan.Principal + loan.InterestAmount
    
            MsgBox("Watts A Loan?" & vbCrLf &
                   "========================" & vbCrLf &
                   "Loan Summary" & vbCrLf &
                   "-------------------------------------" & vbCrLf &
                   "Prepared by:" & vbTab & Clerk.EmployeeNumber & vbCrLf &
                   vbTab & vbTab & Clerk.GetEmployeeName() & vbCrLf &
                   vbTab & vbTab & Clerk.Title & vbCrLf &
                   "Prepared for:" & vbTab & Client.FullName & " - " &
                   Client.PhoneNumber & vbCrLf &
                   "-------------------------------------" & vbCrLf &
                   "Principal:" & vbTab & vbTab & Loan.Principal.ToString("F") & vbCrLf &
                   "Interest Rate:" & vbTab & Loan.InterestRate.ToString("P") & vbCrLf &
                   "Period:" & vbTab & vbTab & CStr(Loan.Period * 12) & " months" & vbCrLf &
                   "Interest Amount:" & vbTab & Loan.InterestAmount.ToString("F") & vbCrLf &
                   "Future Value:" & vbTab & Loan.FutureValue.ToString("F") & vbCrLf &
                   "========================",
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information,
                   "Watts A Loan?")
        End Sub
        Public Function Main() As Integer
            Dim Clerk As Employee = New Employee
            Dim Client As Customer = New Customer
            Dim Loan As LoanInformation = New LoanInformation
    
            MsgBox("This application allows you to evaluate a loan",
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information,
                   "Watts A Loan?")
            IdentifyEmployee()
            IdentifyCustomer()
    
            GetLoanValues()
    
            Show()
            Return 0
        End Function
    
    End Module

Using Separate Files

Instead of just one class or one file, we have learned that, to organize your project, you can create classes in different files. When you debug a project that uses different files that contain procedures and classes, the debugger is aware of the objects and where they are located. As we will learn later, there are various windows that assist you with identifying the objects of your project. As a result, the tools such as the Locals window display their contents accordingly.

As you know already, the starting point of a Visual Basic application is the Main() procedure. If you start debugging an application that uses many code files, the debugger must first identify the file that contains the Main() procedure. If you are debugging a normal console application and if the debugger cannot find a file that contains the Main() function, you would receive an error, indicating that your project does not contain an entry point.

ApplicationApplication: Debugging Classes

  1. To start debugging, on the main menu, click Debug -> Step Into.
    If you don't see the Locals window, on the main menu, click Debug -> Window -> Locals
     
    Debugging
  2. Notice that the debugging yellow arrow indicator is positioned on the left of the Main() function.
    To continue debugging, on the main menu, click Debug -> Step Into
  3. Again, on the main menu, click Debug -> Step Into
  4. Read the message box and click OK
  5. Press F8 three times until a message box comes up
  6. Click OK on the message box.
    Notice that the debugging gets in the body of the IdentifyEmployee() function
  7. To continue, press F8
    Notice that the debugger jumps to the Employee.vb file
  8. In the Locals window, click the + button of Me to expand it. Notice that it shows the member variables of the class
     
    Debugging
  9. To continue debugging, on the Standard toolbar, click the Step Into button Step Into continually to debug the Employee class and observe the values in the Locals window
  10. Continue stepping into until the debugger switches back to the LoanEvaluation.vb file
  11. Press F8 and notice that the IdentifyEmployee() function gets focus
  12. Press F8 again twice
  13. When requested, enter the Employee # as 80226 and click OK
  14. Click the Step Into button Step Into
  15. When asked for the first name, type David and click OK
  16. Press F8
  17. For the last name, type Boyton and click OK
  18. Press F8
  19. For the title, type Shift Supervisor and click OK.
    Observe the values in the Locals window
     
    Debugging
  20. Press F8 a few times until the debugger gets to the Client = IdentifyCustomer() line
  21. To continue, press F8 and observe the debugging
  22. Click OK on the message box
  23. Continue pressing F8 until the Customer.vb file gets focus
  24. Continue pressing F8 until focus gets back to the LoanEvaluation.vb file
  25. In the Locals window, click the + button of Me to expand it
     
    Debugging
  26. Press F8 to continue debugging
  27. When asked for the customer name, type Ann Nanze and click OK
  28. Press F8
  29. When asked for the phone number, type (106) 042-8636 and click OK
  30. To continue debugging, press F8 a few times until a message box comes up
  31. Read the message box and click OK
  32. Press F8 to continue
  33. In the Locals window, click the + button
     
    Debugging
  34. Press F8 twice
  35. When the principal is requested, type 1000 and click OK
  36. Press F8
  37. For the interest rate, type 16.05 and click OK
  38. Press F8
  39. For the period, enter 12 and click OK
     
    Debugging
  40. Press F8
  41. In the Locals window, click the second + button
     
    Debugging
  42. On the Standard toolbar, click the Step Into button Step Into
  43. In the Locals window, expand the nodes
     
    Debugging
  44. Press F8
  45. In the Locals window, expand the las + node to see the current values of the variables
     
    Debugging
  46. Keep pressing F8 continually. Observe the evolution in the Code Editor and the values in the Locals window
  47. When the message box comes up, review it and click OK
     
    Debugging
  48. On the main menu, click File -> Close Solution or File -> Close Project
  49. When asked whether you want to save, click Discard

The Error List

You are probably familiar with the Error List window because if you have ever made any mistake in your code, it would come up. The Error List is a window that displays the list of the current errors in your code. Most of the times, the Error List is present, usually below the Code Editor. At any time, to display it, on the main menu, you can click View -> Error List or press Ctrl + W. While you are working on your code, the Error List may be minimized. To permanently keep it showing, you can click its AutoHide button.

The Error List uses two sequences of how it decides to show the errors. While writing your code, if the live parser, which continuously runs while you are writing your code, finds a problem, it makes a list of all types of violations, even if there is only one mistake, or there appears to be only one mistake. It shows the list in a table:

Error List

Another sequence or a different list may gets created if you build your code. This time, it would be the debugger's list. It is important to know that one mistake could be violating more than one rule of the Visual Basic language.

As seen in our introduction to syntax errors, if you are using Microsoft Visual Basic (whether Microsoft Visual Basic 2010 Express or Microsoft Visual Studio), while you are writing your code, if the parser senses a problem, it underlines the section in the Code Editor and the Error List shows its analysis of that problem. The Error list uses a table made of 5 columns that are Description, File, Line, Column, and Project. You don't have to use all those columns. To specify what columns to show or hide, right-click anywhere in the body of the Error List and position the mouse on Show Columns:

Error List

To show a column, put a check mark on its menu item. To hide a column, remove its check mark. The list of errors displays in an incremental order specified by the parser. Otherwise, you can arrange the order based on a column of your choice. To do this, right-click any entry in the Error List, position the mouse on Sort By, and click the column of your choice.

As mentioned already, the Error List uses various columns to show its findings:

  •  The Description column shows a string that translates some meaning of the problem. The parser and the Error List make an effort to point the actual problem. Sometimes, the error pointed out is not easy to understand. Some other time, the error may not be completely true. Sometimes, if you fix one problem, all the other problems are solved. In our lessons, it is impossible to list all types of errors or all possible types of errors. With experience, you will know how to address and correct them
  • The File column shows the name of the file. This is valuable if your project includes many files
  • The Line column is probably a junior programmer's best friend. The Error List strives to display the line number in code where the problem happened, or probably happened. With experience, you will know that this is not always exact
  • Like the Line number, the Column attempts to exactly point out the character area where the problem occurrent. Also with experience, you will find out that the Error List sometimes shows where it sensed the problem, not necessairy when it happened
  • The Project column gives the name of the project in which the error occurred. This can be valuable if you are working on many projects, or rather on a solution that includes many projects

To jump to an error from the Error List, locate the error and double-click it. The caret would be positioned to that Line number, that character Column or word, and in that File of that Project. If you correct the problem and if the parser concludes that your correction is fine, the error would be automatically removed from the Error List. You can continue this to correct all problems and, eventually, the Error List would be emptied.

 
 
     

Objects Assisting With Debugging

 

The Immediate Window

The Immediate window is a special text editor that can be used to test values, operations (calculations), variables, and (methods of) classes. There are two ways you can get the Immediate window:

  • If you start debugging code from clicking Debug -> Start Debugging (or pressing F5) or Debug -> Step Into (or pressing F8) from the main menu, the Immediate window would come up
  • If you are not debugging, on the main menu, you can click Debug -> Windows -> Immediate

The Immediate window appears as a blank object:

Immediate Window

To use it, you must write something. What you write depends on what you want to test. An expression you write should start with a question mark but in some cases you can omit that symbol. Because the Immediate window is a text editor, you can copy code from somewhere else and paste it in it. If the immediate window starts being crowded, to empty it, you can right-click inside the window and click Clear All.

After typing or pasting the expression, press Enter. The next line would show the result. For example, imagine you want to test an arithmetic operation such as the addition of 248.49 and 57.26, you would type ?248.49 + 57.26 (the empty spaces are optional and you can include as many as you want) and press Enter. Here is an example:

Immediate Window

If you want to test a variable or a function, you must first write code that has the variable. That is, before testing a variable, create a function or use the Main() function and declare the variable in it. If you try testing a variable that is not declared, you would receive an error. One way you can test a variable consists of assigning a certain value, probably a wrong value (called a test value), to it and observe the result. You can start the assignment expression with a question mark but that mark is not necessary. Here is an example:

Immediate Window

The Immediate window allows you to test the value that a variable is currently holding. To get this information, in the Immediate window, type the name of the variable and press Enter:

Immediate Window

If the variable had previously received a value, when you enquire of it in the Immediate window, its current value would show:

Immediate Window

Another test you can perform on a variable consists of adding a value to it to increase it or subtracting a value from it.

To test a procedure in the Immediate window, it must be a function. To get the value that a function is currently returning, type its name preceded by a question mark in the Immediate window and press Enter. Here is an example:

Immediate Window

In the same way, you can create more elaborate functions and test them in the Immediate window.

ApplicationApplication: Using the Immediate Window

  1. To start a new project, on the main menu, click File -> New Project
  2. In the middle list, click Console Application
  3. Change the Name to PayrollEvaluation1
  4. Click OK
  5. On the main menu, click Project -> PayrollEvaluation1 Properties
  6. Click the arrow of the Application Type box and select Windows Forms Application
  7. In the Solution Explorer, right-click Module1.vb and click Rename
  8. Type Evaluation.vb and press Enter twice
  9. Change the document as follows:
    Module Evaluation
    
        Public Function Main() As Integer
            Dim GrossPay As Double
            Dim TimeWorked As Double
            Dim HourlySalary As Double
            Dim TotalDeductions As Double
            Dim NetPay As Double
            Dim Result As String
    
            Result = "Payroll Evaluation" & vbCrLf
    	
            GrossPay = HourlySalary * TimeWorked
            netPay = grossPay - totalDeductions
    
            Result += "===================" & vbCrLf &
                      "Payroll Evaluation" & vbCrLf &
                      "------------------------------" & vbCrLf &
                      "Time Worked:" & vbTab & TimeWorked.ToString("F") & vbCrLf &
                      "Hourly Salary:" & vbTab & HourlySalary.ToString("F") & vbCrLf &
                      "Gross Pay:" & vbTab & vbTab & GrossPay.ToString("F") & vbCrLf &
                      "Deductions:" & vbTab & TotalDeductions.ToString("F") & vbCrLf &
                      "Net Pay:" & vbTab & vbTab & NetPay.ToString("F") & vbCrLf &
                      "==================="
    
            MsgBox(Result,
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information,
                   "Payroll Evalueation")
            Return 0
        End Function
    
    End Module
  10. To execute the application, on the main menu, click Debug -> Start Debugging
     
    Payroll Evaluation
  11. Press Enter to close the message box and return to your programming environment
  12. To step into code, on the main menu, click Debug -> Step Into
  13. If the Imediate window is not displaying, on the main menu, click Debug -> Windows -> Immediate.
    Just in case, right-click inside the Immediate window and click Clear All.
    Click inside the Immediate window
  14. Type TimeWorked = 42.50 and press Enter
  15. Type HourlySalary = 24.65 and press Enter
  16. Type TotalDeductions = 286.50 and press Enter
     
    Immediate Window
  17. If you are using Microsoft Visual Basic 2010 Express, press F11 to step into code.
    If you are using Microsoft Visual Studio, press F8 to step into code
  18. Continue stepping into code until the debugger gets to the Result += "===================" & vbCrLf & line
  19. Click the next empty line in the Immediate window
  20. Type ?GrossPay and press Enter
  21. Type ?NetPay and press Enter
     
    Immediate Window
  22. Press the F8 or F11 key to step into code a few times until the message box displays
     
    Payroll Evaluation
  23. Press Enter to return to Microsoft Visual Basic

The Autos Window

As debugging progresses, sometimes you may want to know the values that the variables are holding on the current and the preceding lines. To give you this information, Microsoft Visual Studio  provides (Microsoft Visual Basic 2010 Express doesn't have) the Autos window. Normally, when you start debugging, the Autos window comes up. If it is hidden while you are debugging, on the main menu, click Debug -> Windows -> Autos.

The Watch Window

Imagine you have a variable that is accessed in various parts of your code. One way you can test the behavior of that variable is to test its value as it circumstancially changes time after time. The Watch window is an object that allows you to monitor the values that a variable (or many variables) holds (or have) in various parts of a method.

To get the Watch window, start debugging your application (Debug -> Start Debugging or Debug -> Step Into). The Watch window would appear, usually next to the Locals window. The Watch window appears as a table with three columns. Their roles will be obvious to you once the window contains something.

To actually use the services of a Watch window, you must create one or more entries, which are referred to as watches. Before creating a watch, you must start stepping into your code, which is done by clicking Debug -> Step Into or by pressing F8 (Microsoft Visual Studio) or F11 (Microsoft Visual Basic 2010 Express). If the Watch window doesn't display in Microsoft Visual Basic 2010 Express, on the main menu, click Debug -> Window -> Watch.

To create a watch, if you are using Microsoft Visual Studio, on the main menu, click Debug -> QuickWatch... In the Expression combo box, type the name of the variable you want to watch. Here is an example:

Quick Watch

You can also type an expression such as a value added to a variable. Here is an example:

Quick Watch

If you want to submit the entry, click the Add Watch button. As an alternatice, in both Microsoft Visual Basic versions, in the Watch window, double-click under the Name header, type either the name of the variable only or an expression that has the variable and an operation, then press Enter.

After creating the desired entries in the Watch window, continue debugging. You will see the values being automatically updated in the Value column of the Watch window.

If you don't need a certain entry in the Watch window, you can remove it, or you can delete all entries in the window. To remove an entry, right-click it and click Delete Watch. To remove all entries, right-click anywhere in the Watch window and click Clear All.

ApplicationApplication: Using the Watch Window

  1. To start debugging, on the main menu, click Debug -> Step Into
  2. If the Watch window is not displaying:
    •  and if you are using Microsoft Visual Basic 2010 Express, on the main menu, click Debug -> Windows -> Watch.
    • If you are using Microsoft Visual Studio, on the Debug toolbar, click Watch 1 (if the Debug toolbar is not available, right-click the Standard toolbar and click Debug)
      Just in case, right-click inside the Watch window and click Clear All
  3. In the Watch window, double-click under Name, type TimeWorked * 1.50 and press Enter (this will be used to evaluate overtime)
  4. Still in the Watch window, click under TimeWorked * 1.50, type HourlySalary + 0.55 and press Enter
  5. Click under HourlySalary + 0.55, type TimeWorked * HourlySalary and press the down arrow key
  6. Type (TimeWorked * HourlySalary) - TotalDeductions and press Enter
     
    Immediate Window
  7. Make sure you have access to the Immediate window.
    Click inside the Immediate window
  8. Type TimeWorked = 7.50 and press Enter
  9. Observe the update in the Watch window
  10. In the Immediate window, click the empty line, type HourlySalary = 18.24 and press Enter
  11. Check the change in the Watch window
  12. In the Immediate window, click the empty line, type TotalDeductions = 38.75 and press Enter
  13. See the result in the Watch window
     
    Immediate Window
  14. Click the next empty line in the Immediate window
  15. Press the up arrow key to see the previously entered lines until you get to TimeWorked. Change it to TimeWorked = 12.50 and press Enter
  16. Press the up arrow key until HourlySalary = 18.24 is selected. Edit it to show HourlySalary = 20.08 and press Enter
     
    Immediate Window
  17. Press F8 or F11 continuously to the end

The IntelliTrace Window

While debugging, you are usually curious to know what line, section, or file is currently being examined:

  • To know the procedure inside of which the current execution is proceeding, you can look into the Code Editor
  • To know the line whose code is executing, in the Code Editor, you can see a yellow right-pointing arrow on its margin
  • Since the lines of code are numbered, to know the number of the line of code that is currently executing, you can look in the right section of the status bar with a label marked with Ln
  • If the project is using more than one file, to know the file whose code is currently executing, you can check the label that has focus in the top bar of the Code Editor

If you are using Microsoft Visual Studio 2010 Ultimate, to get all of this information in one group, you can use a window named IntelliTrace. To get the IntelliTrace window (in Microsoft Visual Studio 2010 Ultimate)

  • On the main menu, click Debug -> Windows -> IntelliTrace Events
  • On the main menu, click Debug -> Intellitrace -> IntelliTrace Events
  • Press Ctrl + Alt + Y, F

ApplicationApplication: Ending the Lesson

  1. On the main menu, click File -> Close Solution (Microsoft Visual Studio) or File -> Close Project (Microsoft Visual Basic 2010 Express)
  2. When asked whether you want to save, click Discard
 
 
   
 

Home Copyright © 2010 FunctionX, Inc.