Assistance with Debugging

Exceptional Debugging

Introduction

As mentioned in the previous lessons, errors will likely occur in your applications. We also know that one way to address them is by handling exceptions. Microsoft Visual Studio can assist you in detecting exceptions.

Practical LearningPractical Learning: Debugging Exceptioons

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle list, click Console App (.Net Framework)
  4. Change the Name to WattsALoan4
  5. Click OK
  6. To create a class, in the Solution Explorer, right-click WattsALoan3 -> Add -> Class...
  7. In the middle list, make sure Class is selected.
    Type Customer as the name of the class/file
  8. Click Add
  9. Change the class as follows:
    namespace WattsALoan3
    {
        public class Customer
        {
            public string FullName    { get; set; }
            public string PhoneNumber { get; set; }
    
            public Customer(string name = "John Doe", string phone = "000-000-0000")
            {
                FullName    = name;
                PhoneNumber = phone;
            }
        }
    }
  10. To create a new class, in the Solution Explorer, right-click WattsALoan3 -> Add -> Class...
  11. Type Employee as the name of the class
  12. Click Add
  13. Change the class as follows:
    namespace WattsALoan3
    {
        public class Employee
        {
            public long   EmployeeNumber { get; set; }
            public string FirstName      { get; set; }
            public string LastName       { get; set; }
            public string Title          { get; set; }
    
            public Employee(long emplNbr = 0,
                            string fName = "Unknown",
                            string lName = " Not Specified",
                            string position = "Loan Specialist")
            {
                LastName       = lName;
                FirstName      = fName;
                EmployeeNumber = emplNbr;
                Title          = position;
            }
    
            public string GetEmployeeName()
            {
                return LastName + ", " + FirstName;
            }
        }
    }
  14. On the main menu, click Project -> Add Class...
  15. Type LoanInformation
  16. Click Add
  17. Change the document ase follows:
    namespace WattsALoan3
    {
        public class LoanInformation
        {
            public double Principal      { get; set; }
            public double InterestRate   { get; set; }
            public double Period         { get; set; }
            public double InterestAmount { get; set; }
            public double FutureValue    { get; set; }
        }
    }
  18. In the Solution Explorer, right-click WattsALoan3 -> Add -> Class...
  19. Type LoanEvaluation as the name of the class
  20. Press Enter
  21. Change the class as follows:
    using static System.Console;
    
    namespace WattsALoan3
    {
        public class LoanEvaluation
        {
            private Employee clerk;
            private Customer client;
            private LoanInformation loan;
    
            public LoanEvaluation()
            {
                clerk = new Employee();
                client = new Customer();
                loan = new LoanInformation();
            }
    
            public void IdentifyEmployee()
            {
                WriteLine("Enter the following pieces of information " +
                                  "about the employee who prepared this loan.");
                Write("Employee #: ");
                clerk.EmployeeNumber = long.Parse(ReadLine());
                Write("First Name: ");
                clerk.FirstName = ReadLine();
                Write("Last Name:  ");
                clerk.LastName = ReadLine();
                Write("Title:      ");
                clerk.Title = ReadLine();
            }
    
            public void IdentifyCustomer()
            {
                WriteLine("Enter the following pieces of information " +
                                  "about the customer for whom this loan was prepared.");
                Write("Customer Name: ");
                client.FullName = ReadLine();
                Write("Phone Number:  ");
                client.PhoneNumber = ReadLine();
            }
    
            public void GetLoanValues()
            {
                WriteLine("Enter the following pieces of information " +
                                  "about the values used for the loan.");
    
                Write("Enter the principal: ");
                loan.Principal = double.Parse(ReadLine());
    
                Write("Enter the interest rate: ");
                loan.InterestRate = double.Parse(ReadLine()) / 100;
    
                Write("Enter the number of months: ");
                loan.Period = double.Parse(ReadLine()) / 12;
            }
    
            public void Show()
            {
                loan.InterestAmount = loan.Principal * loan.InterestRate * loan.Period;
                loan.FutureValue = loan.Principal + loan.InterestAmount;
    
                WriteLine("======================================");
                WriteLine("Loan Summary");
                WriteLine("=------------------------------------=");
                WriteLine("Prepared by:  {0} - {1}\n              {2}",
                                  clerk.EmployeeNumber,
                                 clerk.GetEmployeeName(), clerk.Title);
                WriteLine("=------------------------------------=");
                WriteLine("Prepared for: {0}\n              {1}",
                                  client.FullName, client.PhoneNumber);
                WriteLine("=------------------------------------=");
                WriteLine("Principal:       {0:F}", loan.Principal);
                WriteLine("Interest Rate:   {0:P}", loan.InterestRate);
                WriteLine("Period For:      {0} months", loan.Period * 12);
                WriteLine("Interest Amount: {0:F}", loan.InterestAmount);
                WriteLine("Future Value:    {0:F}", loan.FutureValue);
                WriteLine("======================================");
            }
        }
    }
  22. In the Solution Explorer, right-click Program.cs and click Rename
  23. Type WattsALoan to get WattsALoan.cs, and press Enter
  24. Read the text in the message box and click Yes
  25. Click the WattsALoan.cs tab to access it and change its document as follows:
    using static System.Console;
    
    namespace WattsALoan3
    {
        public class WattsALoan
        {
            public static int Main(string[] args)
            {
                LoanEvaluation evaluation = new LoanEvaluation();
    
                Title = "Watts A Loan?";
    
                WriteLine("This application allows you to evaluate a loan");
                evaluation.IdentifyEmployee();
                evaluation.IdentifyCustomer();
    
                Clear();
    
                evaluation.GetLoanValues();
    
                Clear();
    
                evaluation.Show();
                return 0;
            }
        }
    }
  26. On the main menu, click Debug -> Start Debugging
  27. In the DOS prompt, for the Employee #, type Unknown and press Enter. Notice the pointing exception in the Code Editor

    Debugging - Stepping Into

  28. On the Debug toolbar, click Click the Stop Debugging button
  29. Click the LoanEvaluation.cs tab to access it
  30. Click the margin on the left side of loan.FutureValue = loan.Principal + loan.InterestAmount;

    Debugging - The Code Editor

  31. On the main menu, click Window-> Employee.cs
  32. Click the margin on the left site of return LastName + ", " + FirstName;

    Debugging - The

  33. On the main menu, click Debug -> Start Debugging

    Debugging - Stepping Into

  34. In the DOS window, enter the values as follows and press Enter after each. While you are typing, observe how focus moves among the tabs and the lines in the Code Editor. In the Locals window, expand everything and observe the changing values in the rows
     
    Employee #: 41920
    First Name: Donna
    Last Name: Jones
    Title: Accounts Manager
    Customer Name: Hermine Simms
    Customer Phone: 410-573-2031
    Principal: 3250
    Interest Rate 14.85
    Number of Months: 36

    The focus moves to the LoanEvaluation.cs document in the Code Editor
  35. Press F5 to continue.
    Debugging switches to the Employee.cs tab and to the line that that was marked
  36. Press F5 to see the result in the DOS window

    Debugging - Stepping Into

  37. Press Enter to close the window and return to your programming environment

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, 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, gets created if you build your code. It is important to know that one mistake could be violating more than one rule of the C# language.

As seen in our introduction to syntax errors, if you are using 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 many 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:

To jump to an error from the Error List, locate its entry in the Error List window and double-click it. The caret would be positioned to that Line number 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 removed automatically 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. To display the Immediate window, 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 method, you must first write code that has the variable. That is, before testing a variable, create a method 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, 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 preceded by a question mark (you can also just 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 method in the Immediate window, the method should return a value. To get the value that a mehod is currently returning, type its name in the Immediate window and press Enter. You can also precede the name of the method with a question mark. Here is an example:

Immediate Window

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

Practical LearningPractical Learning: 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 App (.NET Framework)
  3. Change the Name to PayrollEvaluation1
  4. Click OK
  5. In the Solution Explorer, right-click Program.cs and click Rename
  6. Type PayrollEvaluation to get PayrollEvaluation.cs, and press Enter
  7. Read the text in the message box and click Yes
  8. Change the document as follows:
    using static System.Console;
    
    namespace PayrollEvaluation1
    {
        public class PayrollEvaluation
        {
            public static int Main(string[] args)
            {
                double grossPay = 0;
                double timeWorked = 0;
                double hourlySalary = 0.00;
                double totalDeductions = 0.0;
                double netPay = 0.00;
    
                Title = "Payroll Evaluation";
    
                grossPay = hourlySalary * timeWorked;
                netPay = grossPay - totalDeductions;
                Clear();
    
                WriteLine("=======================");
                WriteLine("Payroll Evaluation");
                WriteLine("-----------------------");
                WriteLine("Time Worked:   {0, 7}", timeWorked.ToString("F"));
                WriteLine("Hourly Salary: {0, 7}", hourlySalary.ToString("F"));
                WriteLine("Gross Pay:     {0, 7}", grossPay.ToString("F"));
                WriteLine("Deductions:    {0, 7}", totalDeductions.ToString("F"));
                WriteLine("Net Pay:       {0, 7}", netPay.ToString("F"));
                WriteLine("=======================\n");
    
                ReadKey();
                return 0;
            }
        }
    }
  9. To execute the application, on the main menu, click Debug -> Start Debugging.
    Notice that all values are 0:

    Payroll Evaluation

  10. Press Enter to close the DOS window and return to your programming environment
  11. To step into code, on the main menu, click Debug -> Step Into
  12. On the main menu, click Debug -> Windows -> Immediate.
    Just in case, right-click inside the Immediate window and click Clear All.
    Press F11 to step into code

    Payroll Evaluation

  13. Continue pressing the F11 key (4 times) to step into code until you get to the line double netPay = 0.00;
  14. Click inside the Immediate window
  15. Type timeWorked = 42.50 and press Enter

    Payroll Evaluation

  16. Type hourlySalary = 24.65 and press Enter
  17. Type totalDeductions = 286.50 and press Enter

    Payroll Evaluation

  18. Press F11 four times to step into code until you get to the line that has Clear();

    Payroll Evaluation

  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 F11 key to step into code a few times until the DOS window gets focus and displays the whole summary

    Immediate Window

  23. Keep pressing F11 continuously until the DOS window closes and return to your programming environment

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 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.

Practical LearningPractical Learning: Using the Immediate Window

  1. To start debugging the application again, on the main menu, click Debug -> Step Into
  2. On the main menu, click Debug -> Windows -> Autos
  3. Right-click inside the Immediate window and click Clear All:

    Payroll Evaluation

  4. Press F11 to step into code
  5. Continue pressing the F11 key twice

    Payroll Evaluation

  6. Press F11 three times to step into code until you get to the line double netPay = 0.00;
  7. Click inside the Immediate window
  8. Type timeWorked = 38 and press Enter
  9. Type hourlySalary = 18.85 and press Enter
  10. Type totalDeductions = 244.79 and press Enter

    Payroll Evaluation

  11. Press F11 two times and observe the rows in the Autos window

    Payroll Evaluation

  12. Press F11 and observe the rows in the Autos window

    Payroll Evaluation

  13. Press F11 twice to get to the line that has Clear();
  14. Click the next empty line in the Immediate window
  15. Type ?grossPay and press Enter
  16. Type ?netPay and press Enter

    Immediate Window

  17. Press the F11 key to step into code a few times until the DOS window gets focus and displays the whole summary
  18. Keep pressing F11 continuously until the DOS window closes and return to your programming environment

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 can be done by clicking Debug -> Step Into or by pressing F11.

To create a watch, remember that you must first Step Into your code, then 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 Microsoft Visual Studio, 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.

Practical LearningPractical Learning: Using the Watch Window

  1. To start debugging, on the main menu, click Debug -> Step Into
  2. If the Watch window is not displaying, on the main menu, click Debug -> Quick -> Watch -> Watch 1.
    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

    Watch

  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

    Immediate 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

    Immediate 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 last line (the first empty line) in the Immediate window
  15. Press the up arrow key to access the previously entered lines (the text lines you had typed will be displaying one after the other) until you get timeWorked
  16. Change it to timeWorked = 12.75 and press Enter

    Immediate Window

  17. Press the up arrow key until hourlySalary = 18.24 is selected
  18. Edit it to show hourlySalary = 26.16 and press Enter

    Immediate Window

  19. Press F11 continuously while observing the Watch 1 window, until you get to the end of code and the DOS window closes

The IntelliTrace Window

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

If you are using Microsoft Visual Studio 2013 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 2013 Ultimate only)

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2010-2019, FunctionX Next