Errors in a Program

Introduction

Apparently no matter how careful and meticulous you are, there will be errors in your program. When, not if, they occur, you should be able to address the issue. In most cases, both C# and Microsoft Visual C# can assist you.

The errors your program will encounter can be classified in three categories: runtime, syntax, and logic errors. We will study runtime errors in the next two lessons about exception handling.

Practical LearningPractical Learning: Introducing Errors

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New -> Project...
  3. In the middle list, click Empty Project (.Net Framework)
  4. Change the Name to WattsALoan2
  5. Click OK
  6. In the Solution Explorer, right-click WattsALoan2 -> Add -> New Item...
  7. In the left list of the Add New Item dialog box, click Code
  8. In the middle list, click Code File
  9. Change the file Name to LoanEvaluation
  10. Press Enter
  11. In the document, type the following:
    using static System.Console;
    
    public class LoanEvaluation
    {
        public static void Main()
        {
            double principal = 0.00;
    
            Title = "Watts' A Loan";
    
            WriteLine("============================");
            WriteLine("Loan Summary");
            WriteLine("=--------------------------=");
            WriteLine("Principal:       {0:F}", principal);
            WriteLine("============================");
            
            Console.ReadKey();    
        }
    }

Syntax Errors

A syntax error is due to a misuse of the C# language in your code. For example, we know that, on one hand C# is case-sensitive and, on the other C# has a set of keywords that you should not use to name your variables. The first rule can be difficult to observe if you come from a case-insensitive language. It can also happen through distraction. The second rule is easy to observe if you have used another C-based language such as C++ or Java. Both rules are easy to violate if you write your code using a normal text editor like Notepad.

Fortunately, the built-in Code Editor of Microsoft Visual Studio makes it extremely easy to be aware of syntax errors as soon as they occur:

As you can see, if you create your application in Microsoft Visual Studio, the Code Editor is fully equipped with tools to assist you to detect and correct syntax errors. If you still violate a syntax rule, when you build your project, the compiler would detect the error and point out the line, the section, and the file name where the error occurred. Here is an example:

Operator Misuse

Operator Misuse

Logic Errors

A logic error occurs when the program (the code) is written well but the result it produces is not reliable. With a logic error, the Code Editor does not see anything wrong in the document and therefore cannot point out a problem. One of the worse types of logic errors is one that makes a computer crash sometimes, regularly, or unpredictably, while there is nothing obviously wrong in the code.

Logic errors are, or can be, difficult to detect because you will have to know for sure that the result is wrong and why (and sometimes worse, you will have to agree or accept that it is your program that is causing a problem in the computer). Because you or the user of your program would know with certainty that the result is questionable, you would have to use some means of correcting it. One of the techniques you can use is referred to as debugging.

Debugging Fundamentals

Introduction

A logic error is called a bug. Debugging is the process of examining code to look for bugs or to identify problems. Debugging is the ability to monitor the behavior of a variable, a class, or (one of) its member(s) throughout a program. Microsoft Visual Studio provides many features to perform debugging operations.

The debugger is the program you use to debug your code. The code or application that you are debugging is called the debuggee.

Probably the most fundamental way of examining code is to read every word and every line, with your eyes, using your experience as a programmer. This can work for short code written in one file and/or in one class. If the code to examine covers many pages or many files, it could be difficult and tiresome to examine code with your eyes line by line. Fortunately, to assist you with this operation, Microsoft Visual Studio provides various tools and windows that you use, one window or a combination of objects.

Starting and Continuing With Debugging

There are different ways you can launch the debugging process:

In later sections, we will see other ways of starting or proceeding with debugging. In some cases, we will see how you can suspend debugging. When this has happened, to resume debugging:

We will see other ways of continuing with debugging.

Stopping the Debugging

As we will see in later sections, there are various debugging approaches available in Microsoft Visual Studio. Sometimes you will want to suspend or stop debugging.

To end debugging at any time:

The Locals Window

One of the primary pieces of information you want to get is the value that a variable is holding. A window named Locals is used to show that value. Normally, when you start debugging, the Locals window shows automatically. During debugging, if the Locals window is hidden, to display it:

As its name indicates, the Locals window shows the values of local variables as they are changed. If there is more than one variable, the Locals window displays their names and gives a row to each variable. The Locals window organizes its information in a table or grid:

Locals

The Name column shows the name of each variable declared in the method or the section that is being debugged.

The Value columns shows the value of each variable. When debugging starts, each variable shows its default or initial value. As debugging progresses, when a variable acquires a new value, the Locals window updates it in the Value column. In some cases, instead of the debugger changing the value, you can manually select and change it in the Locals window and press Enter.

The Type column shows the data type of the variable. If the variable is a class, the name of the class shows in the Type column.

Debugging Statements

Executing One Statement at a Time

Just as done when reading code with your eyes, the most basic way to monitor code is to execute one line at a time and see the results displayed before your eyes. To support this operation, the debugger provides what is referred to as stepping into.

To execute code one line at a time, while the file that contains it is displaying:

When code is being stepped into, the margin corresponding to the line that is being examined displays a right-pointing yellow arrow:

Debugger

This lets you know what line is currently considered.

Practical LearningPractical Learning: Examining Local Variables

  1. While the Code Editor is displaying the code you typed, on the main menu, click Debug -> Step Into:

    Right

    If the Locals window is not displaying, on the main menu, click Debug -> Window -> Locals
  2. To perform the instructions in this section, move the windows to make sure you can see the Code Editor, the Locals window, and the DOS window. Here is an example:

    Debugging

  3. Notice the yellow arrow button on the left in the margin.
    Notice that the Locals window displays one entry: the principal variable.
    Notice that the DOS window shows a blinking caret.
    To end debugging, on the main menu, click Debug -> Stop Debugging
  4. Change the code as follows:
    uusing static System.Console;
    
    namespace WattsALoan2
    {
        public class LoanEvaluation
        {
            public static void Main(string[] args)
            {
                double principal;
                double interestRate;
                double period;
                double interestAmount;
                double futureValue;
    
                Title = "Watts' A Loan";
    
                WriteLine("This application allows you to evaluate a loan.");
                WriteLine("To proceed, enter the following values.");
    
                Write("Enter the principal: ");
                principal = double.Parse(ReadLine());
                Write("Enter the interest rate: ");
                interestRate = double.Parse(ReadLine()) / 100;
                Write("Enter the number of months: ");
                period = double.Parse(ReadLine()) / 12;
    
                interestAmount = principal * interestRate * period;
                futureValue = principal + interestAmount;
    
                Clear();
    
                WriteLine("============================");
                WriteLine("Loan Summary");
                WriteLine("=--------------------------=");
                WriteLine("Principal:       {0:F}", principal);
                WriteLine("Interest Rate:   {0:P}", interestRate);
                WriteLine("Period For:      {0} months", period * 12);
                WriteLine("Interest Amount: {0:F}", interestAmount);
                WriteLine("Future Value:    {0:F}", futureValue);
                WriteLine("============================");
            
                ReadKey();
            }
        }
    }
  5. To restart debugging, on the main menu, click Debug -> Step Into.
    Notice that the Locals window displays a list of the local variables and their starting values:

    Debugging

  6. To continue debugging, on the Standard toolbar, click the Step Into button Step Into:

    Debugging

  7. To continue debugging, press F11:

    Debugging

  8. Press F11 until the focus moves to the DOS window:

    Debugging Watts A Loan

  9. Press F11 again To display the second line of text
  10. Press F11 again:

    Debugging Watts A Loan

  11. When asked to enter a value for the principal, type 6500 and press Enter:

    Debugging Watts A Loan

  12. Notice that the focus moves back to the Code Editor.
    Notice that the value of the principal has changed in the Locals grid.
    Press F11
  13. Press F11 again
  14. When the focus moves to the DOS window, when you are asked to provide the interest rate, type 12.65 and press Enter.
    The focus moves back to the Code Editor.
    Notice that the value of the interestRate variable in the Locals window has changed:

    Debugging Watts A Loan

  15. Press F11
  16. Press F11 again
  17. The focus moves to the DOS window. When the number of months is requested, type 36 and press Enter.
    The focus moves back to the Code Editor.
    Notice that the value of the period variable in the Locals window has been changed:

    Debugging Watts A Loan

  18. Press F11:

    Debugging Watts A Loan

  19. Press F11:

    Debugging Watts A Loan

  20. press F11:

    Debugging Watts A Loan

  21. Continue pressing F11 until the DOS window displays the loan summary section
    ============================
    Loan Summary
    =--------------------------=
    Principal:       6500.00
    Interest Rate:   12.65 %
    Period For:      36 months
    Interest Amount: 2466.75
    Future Value:    8966.75
    ============================

    Debugging Watts A Loan

  22. Press F11 to end the debugging, closing the DOS window and returning to your programming environment

Executing One Method at a Time

The Step Into feature is a good tool to monitor the behavior of variables inside a method. This also allows you to know if a method is behaving as expected. Once you have established that a method is alright, you may want to skip it. Instead of executing one line at a time, the debugger allows you to execute a whole method at a time or to execute the lines in some methods shile skipping the others. To support this, you use a feature named Step Over.

To step over a method, while debugging:

As its name suggests, the Step Over feature allows you to skip a method if you know it doesn't have any problem. When debugging, you choose what methods to step into and which ones to step over.

Practical LearningPractical Learning: Stepping Over

  1. Change the document as follows:
    using static System.Console;
    
    namespace WattsALoan2
    {
        public class LoanEvaluation
        {
            private static double GetPrincipal()
            {
                double value = 0.00;
    
                Write("Enter the principal: ");
                value = double.Parse(ReadLine());
    
                return value;
            }
    
            private static double GetInterestRate()
            {
                double value = 0.00;
    
                Write("Enter the interest rate: ");
                value = double.Parse(ReadLine());
    
                return value;
            }
    
            private static double GetPeriods()
            {
                double value = 0;
    
                Write("Enter the number of months: ");
                value = double.Parse(ReadLine());
    
                return value;
            }
    
            public static void ShowLoanSummary(double presentValue,
                                               double annualRate,
                                               double periods,
                                               double interestCollected,
                                               double totalCollected)
            {
                WriteLine("============================");
                WriteLine("Loan Summary");
                WriteLine("=--------------------------=");
                WriteLine("Principal:       {0:F}", presentValue);
                WriteLine("Interest Rate:   {0:P}", annualRate);
                WriteLine("Period For:      {0} months", periods * 12);
                WriteLine("Interest Amount: {0:F}", interestCollected);
                WriteLine("Future Value:    {0:F}", totalCollected);
                WriteLine("============================");
            }
    
            public static void Main(string[] args)
            {
                double principal;
                double interestRate;
                double period;
                double interestAmount;
                double futureValue;
    
                Title = "Watts' A Loan";
    
                WriteLine("This application allows you to evaluate a loan.");
                WriteLine("To proceed, enter the following values.");
    
                principal = GetPrincipal();
                interestRate = GetInterestRate() / 100;
                period = GetPeriods() / 12;
    
                interestAmount = principal * interestRate * period;
                futureValue = principal + interestAmount;
    
                Clear();
    
                ShowLoanSummary(principal, interestRate, period, interestAmount, futureValue);
            
                Console.ReadKey();
            }
        }
    }
  2. To debug, on the main menu, click Debug -> Step Into:

    Debugging Watts A Loan

    Notice that the yellow button is positioned in the first line under Main()
  3. To continue, on the Debug toolbar, keep clicking the Step Into button Step Into (9 times) until the caret is blinking in the DOS window requesting the principal
  4. When asked to provide a Principal, type 21650 and press Enter:

    Debugging Watts A Loan

  5. Press F11 to continue.:

    Debugging Watts A Loan

  6. Press F11 and notice that the debugger gets in the interestRate = GetInterestRate() / 100; line
  7. Press F11 and notice that the caret moves to the body of the GetInterestRate() method
  8. Keep pressing F11 while inside the GetInterestRate() method, until the DOS window receives focus
  9. When prompted for an interest rate, type 8.95 and press Enter:

    Debugging Watts A Loan

  10. Press F11 to get to the last line of the GetInterestRate() method
  11. Press F11 to get back to the interestRate = GetInterestRate() / 100; line
  12. Press F11 to continue
  13. Press F11 to get to the period = GetPeriods() / 12; line
  14. Press F11 to get to the body of the GetPeriods() method
  15. Press F11 4 times until the DOS window receives focus and the caret is blinking in it
  16. When prompted fo the number of months, type 60 and press Enter:

    Debugging Watts A Loan

  17. Press F11 to move to the last line of the GetPeriods() method
  18. Press F11 to get back to the period = GetPeriods() / 12; line
  19. Press F11 to get to the interestAmount = principal * interestRate * period; line
  20. Press F11 to get to the futureValue = principal + interestAmount; line
  21. Press F11 to get to the Clear(); line
  22. Press F11 to get to the ShowLoanSummary(principal, interestRate, period, interestAmount, futureValue); line
  23. Press F11 to get to the body of the ShowLoanSummary() method
  24. Keep pressing F11 to navigate to the line inside the ShowLoanSummary() method:

    Debugging Watts A Loan

  25. Press F11 until the DOS window is closed
  26. Cloee your programming environment

Previous Copyright © 2010-2019, FunctionX Next