Home

Errors and Exceptions: Introduction to Errors and Debugging

  

Errors in a Program

 

Introduction

 

Problems happen in a program. Some of them manifest themselves while you are developing your project. Some others would show up during the lifetime of your application. This seams to be an avoidable fact of life. The errors your program will encounter can be classified in three categories: runtime, syntax, and logic errors.

HomeApplication: 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 Console Application
  4. Change the Name to WattsALoan1
  5. Click OK
  6. On the main menu, click Project -> WattsALoan1 Properties
  7. Click the arrow of the Application Type box and select Windows Forms Application
  8. In the Solution Explorer, right-click Module1.vb and click Rename
  9. Type LoanEvaluation.vb and press Enter twice
  10. Change the document as follows:
    Module LoanEvaluation
    
        Public Function Main() As Integer
            Return 0
        End Function
    
    End Module

Syntax Errors

A syntax error is due to a misuse of the Visual Basic language in your code. For example, the Visual Basic language has a set of keywords that you should (must) not use to name your variable. This rule is usually easy to respect if you are using a professional text editor such as the Code Editor of Microsoft Visual Basic.

The Code Editor of Microsoft Visual Basic makes it easy to be aware of syntax errors as soon as they occur:

  • When you start typing code, the IntelliSense starts building a list of words that match the first characters and those that include the characters already typed:
     
    Code Completion

    If you see a word you need and it is highlighted, you can press Enter to select it. You can also double-click the word from the list. If the list is long and the word does not appear yet, you can keep typing (adding characters) until the word you want comes up
  • If you mistype a word or a keyword, the Code Editor would indicate the error by underlining the word. If you place the mouse on it, a message would display the reason for the error:
     
    Code Completion
  • If you declare a variable, or once you have declared a variable, whenever you want to use it, as soon as you start typing its name, the IntelliSense would display a list that includes that variable
     
    Variable Completion
  • The Visual Basic language is equipped with many operators and each operator has rules. If you misuse an operator, the section of your code would be underlined. You can position the mouse on it to see the resulting error message:
     
    Operator Misuse

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 (we will come back to this in the next lesson).

HomeApplication: Introducing Syntax Errors

  • Change the document as follows:
    Module LoanEvaluation
    
        Public Function Main() As Integer
            Dim Summary As String
            Dim Principal As Double = 0.0
    
            Summary = "Watts A Loan?" & vbCrLf
    
            Summary += "============================" & vbCrLf
            Summary += "Loan Summary" & vbCrLf
            Summary += "=------------------------------------------=" & vbCrLf
            Summary += String.Format("Principal:       {0:F}" & vbCrLf, Principal)
            Summary += "============================"
    
            MsgBox(Summary)
            Return 0
        End Function
    
    End Module

Logic Errors

A logic error occurs when the program (the code) is written fine 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 spot 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; imagine a user reports that her computer crashes every time she starts the application you created). 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 function, or another item throughout a program. Microsoft Visual Basic 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 in one class. If the code to examine covers many pages or many files, it could be aweful 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. One of the tools you can use is the Standard toolbar that is equipped with various debugging buttons:

Standard Toolbar

Starting and Continuing With Debugging

There are different ways you can launch the debugging process:

  • On the main menu, you can click Debug -> Start Debugging
  • On the Standard toolbar, you can click the Start Debugging button Start Debugging
  • In the Solution Explorer, you can right-click the name of the project, position the mouse on Debug, and click Step Into New Instance
  • You can press F5

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:

  • On the main menu, you can click Debug -> Continue
  • On the Standard toolbar, you can click the Continue button Continue
  • You can press F5

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:

  • On the main menu, click Debug -> Stop Debugging
  • On the Standard toolbar, click the Stop Debugging button Stop Debugging

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 can be 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:

  • On the main menu, click Debug -> Windows -> Locals
  • Press Ctrl + Alt + V, release, then press L

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. If the variable is a class, a + button appears to its left, indicating that it has fields (member variables):

Locals

In this case, to show the variables, that is, to expand the node, click the + button. This would show the fields under the variable name and the name of the class between curly brackets under the Value column:

Locals

The Value columns shows the value of each variable. When debugging starts, each variable shows its default 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. 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:

  • On the main menu, click Debug -> Step Into
  • On the Standard toolbar, click the Step Into button Step Into
  • In you are using Microsoft Visual Studio, press F8.
    If you are using Microsoft Visual Basic 2010 Express, press F11

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

Debugger

This lets you know what line is currently considered.

ApplicationApplication: Examining Local Variables

  1. While the Code Editor is displaying the code you typed, on the main menu, click Debug -> Step Into
  2. To display the Locals window, on the main menu, click Debug -> Window -> Locals
     
    Debugging
  3. Notice the yellow arrow button in the margin.
    Notice that the Locals window displays the name of the Main function and the variables in the function.
    To end debugging, on the main menu, click Debug -> Stop Debugging
  4. Change the code as follows:
    Module LoanEvaluation
    
        Public Function Main() As Integer
            Dim Summary As String
            Dim Principal As Double
            Dim InterestRate As Double
            Dim Period As Double
            Dim InterestAmount As Double
            Dim FutureValue As Double
    
            Summary = "This application allows you to evaluate a loan." & vbCrLf
            Summary += "To proceed, enter the following values" & vbCrLf
            MsgBox(Summary,
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information,
                   "Watts A Loan?")
    
            Principal = CDbl(InputBox("Enter the principal: ",
                                      "Watts A Loan?", "0.00"))
            InterestRate = CDbl(InputBox("Enter the interest rate: ",
                                      "Watts A Loan?", "0.00")) / 100
            Period = CDbl(InputBox("Enter the number of months: ",
                                      "Watts A Loan?", "0.00")) / 12
    
            InterestAmount = Principal * InterestRate * Period
            FutureValue = Principal + InterestAmount
    
            Summary = "Watts A Loan?" & vbCrLf
            Summary += "========================" & vbCrLf
            Summary += "Loan Summary" & vbCrLf
            Summary += "-------------------------------------" & vbCrLf
            Summary += "Principal:" & vbTab & vbTab & Principal.ToString("F") & vbCrLf
            Summary += "Interest Rate:" & vbTab & InterestRate.ToString("P") & vbCrLf
            Summary += "Period:" & vbTab & vbTab & CStr(Period * 12) & " months" & vbCrLf
            Summary += "Interest Amount:" & vbTab & InterestAmount.ToString("F") & vbCrLf
            Summary += "Future Value:" & vbTab & FutureValue.ToString("F") & vbCrLf
            Summary += "========================"
    
            MsgBox(Summary,
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information,
                   "Watts A Loan?")
            Return 0
        End Function
    
    End Module
    
  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:
     
    Locals
  6. To continue debugging, on the Standard toolbar, click the Step Into button Step Into
  7. To continue debugging, press F8 twice
     
    Locals
  8. Keep pressing F8 until a message box displays
     
    Watts A Loan
  9. Click OK
  10. Keep pressing F8 until an input box displays
  11. When asked to enter a value for the principal, type 6500 and press Enter
     
    Locals
  12. When you are asked to provide the interest rate, type 12.65 and press Enter
     
    Locals
  13. Press F8
  14. Press F8 again
  15.  When the number of months is requested, type 36 and press Enter.
    Notice that the value of the period variable in the Locals window has been changed
     
    Locals
  16. Press F8
     
    Locals
  17. Press F8
     
    Locals
  18. Press F8
     
    Locals
  19. Continue pressing F8 until the Summary message box displays
     
    Watts A Loan
  20. Click OK to close the message box
 

Running to a Point

When executing a program, you can specify a section or line where you want the execution to pause, for any reason you judge necessary. This approach is useful if you have checked code up to a certain point and it looked alright. If you are not sure about code starting at a certain point, this can be your starting point.

To execute code up to a certain point

  • Right-click the line and click Run to Cursor
  • Press Ctrl + F8

HomeApplication: Running to a Point

  1. In the code, right-click the Summary = "Watts A Loan?" & vbCrLf line and click Run To Cursor
  2. When requested, enter the following values. Press Enter after entering each value. While you are entering them, check the moving button in the Code Editor and observe the values in the Locals window:
     
    Principal 2450.00
    Interest Rate 10.15
    Period 28

    Locals
  3. Press F5 to continue
 
 
     

Breakpoints

A breakpoint on a line is the code where you want the exection to suspend. You must explicitly specify that line by creating a breakpoint. You can aslo create as many breakpoints as you want. You can also remove a breakpoint you don't need anymore.

To create a breakpoint, first identify the line of code where you want to add it. Then:

  • In the left margin corresponding to the line, click
  • On the main menu, click Debug -> Toggle Breakpoint
  • Right-click the line, position the mouse on Breakpoint, and click Insert Breakpoint
  • Click anything on the line and press F9

A breakpoint is represented by a red circular button Breakpoint. After creating a breakpoint, when code executes and reaches that line, it would pause and let you know by drawing a right-pointing yellow button Breakpoint.

After using a breakpoint, you can remove it. To delete a breakpoint:

  • Click the breakpoint in the margin
  • Right-click the line that has the breakpoint, position the mouse on Breakpoint, and click Delete Breakpoint
  • Click anything on the line that has the breakpoint:
    • On the main menu, click Debug -> Toggle Breakpoint
    • Press F9

Remember that you can create more than one breakpoint. If you have more than one breakpoint in your code, execution would pause at each one of them. At any time, you can remove one or all breakpoints. To delete all breakpoints, on the main menu, click Debug -> Delete all Breakpoints.

ApplicationApplication: Using Breakpoints

  1. In the Code Editor, click the margin on the left side of FutureValue = Principal + InterestAmount
     
    Inserting a Breakpoint
  2. On the main menu, click Debug -> Start Debugging
  3. Click OK on the message box
  4. When asked, enter the values as follows and press Enter after each
     
    Principal 1500
    Interest Rate 15.55
    Period 24

    Locals
  5. Press F5 to continue
     
    Watts A Loan
  6. In the Code Editor, click the FutureValue = Principal + InterestAmount line
  7. On the main menu, click Debug -> Toggle Breakpoint
  8. In the Code Editor, click the Principal = CDbl(InputBox("Enter the principal: ", line
  9. On the main menu, click Debug -> Toggle Breakpoint
  10. In the Code Editor, right-click the Summary = "Watts A Loan?" & vbCrLf line, position the mouse on Breakpoints, and click Insert Breakpoint
     
    Locals
  11. To execute, press F5
  12. Click OK on the message box.
    Notice the first breakpoint has changed
     
    Locals
  13. To continue, press F5
  14. When asked, enter the values as follows and press Enter after each
     
    Principal 17500
    Interest Rate 9.75
    Period 48

    Locals
  15. Press F5 to continue
     
    Watts A Loan
  16. Click OK to close the message box

Stepping to Breakpoints

You can combine the Step Into feature with breakpoints. That is, you can examine each code line after line until you get to a specific line. This allows you to monitor the values of variables and see their respective values up to a critical section. To do this, first create one or more breakpoints, then proceed with Step Intos of your choice.

ApplicationApplication: Stepping to Breakpoints

  1. Make sure the previous two breakpoints are still selected.
    To start debugging, on the main menu, click Debug -> Step Into.
    Make sure you can see the Code Editor and the Locals window
  2. Press F8 continually until the message box displays
  3. Click OK on the message box
  4. To continue, press F8 to step into
  5. Enter the principal as 3525.75 and click OK
  6. Press F8 to continue
  7. Enter the interest rate as 13.75 and click OK
  8. Press F8 to continue
  9. Enter the period as 32 and click OK
  10. Press F5 twice to continue
  11. Click OK on the message box

Executing One Method at a Time

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

To step over a method, while debugging:

  • On the main menu, click Debug -> Step Over
  • On the Standard toolbar, click the Step Over button Step Over
  • Press Shift + F8

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

ApplicationApplication: Stepping Over

  1. Change the document as follows:
    Module LoanEvaluation
        Private Sub Announce()
            MsgBox("This application allows you to evaluate a loan." & vbCrLf &
                   "To proceed, enter the following values" & vbCrLf,
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information,
                   "Watts A Loan?")
        End Sub
    
        Private Function GetPrincipal() As Double
            Dim PresentValue As Double
    
            REM Price of a car
            PresentValue = 22755.85
    
            Return PresentValue
        End Function
    
        Private Function GetInterestRate() As Double
            Dim Rate As Double
    
            Rate = 14.55
    
            Return Rate
        End Function
    
        Private Function GetPeriod() As Integer
            Dim Months As Integer
    
            Months = 60
    
            Return Months    
        End Function
    
        Public Function Main() As Integer
            Dim Principal As Double
            Dim InterestRate As Double
            Dim Period As Double
            Dim InterestAmount As Double
            Dim FutureValue As Double
    
            Announce()
            Principal = GetPrincipal()
            InterestRate = GetInterestRate()
            Period = GetPeriod()
            
            Return 0
        End Function
    
    End Module
  2. To debug, on the main menu, click Debug -> Step Into.
    Notice that the yellow button is positioned in the margin on the left of the Main() function
  3. To continue debugging, on the Standard toolbar, click the Step Into button Step Into four times
  4. Click OK on the message box
  5. Click the Step Into button Step Into again two times.
    Notice the yellow margin button is positioned on Principal = GetPrincipal()
  6. Click the Step Into button Step Into and notice that the yellow-point button is positioned on the starting point of the GetPrincipal() function
  7. Click the Step Into button Step Into again.
    Notice that the debugging is continuing in the body of the GetPrincipal() function and visits each line
  8. Click the Step Into button Step Into again three times to complete debugging the GetPrincipal() function
  9. To stop the debugging, on the Standard toolbar, click the Stop Debugging button Stop Debugging
  10. To debug, on the main menu, click Debug -> Step Into.
    Notice that the yellow button is positioned in the margin
  11. To continue, on the Standard toolbar, click the Step Into button Step Into four times
  12. Click OK on the message box
  13. Click the Step Into button Step Into twice until the yellow margin button is positioned on the Principal = GetPrincipal() line
  14. To skip the GetPrincipal() function, on the main menu, click Debug -> Step Over.
    Notice that, this time, the body of the GetPrincipal() function is skipped
  15. Click the Step Into button Step Into
  16. To stop the debugging, on the main menu, click Debug -> Stop Debugging
  17. Change the document as follows:
    Module LoanEvaluation
        Private Sub Announce()
            MsgBox("This application allows you to evaluate a loan." & vbCrLf &
                   "To proceed, enter the following values" & vbCrLf,
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information,
                   "Watts A Loan?")
        End Sub
    
        Private Function GetPrincipal() As Double
            Dim PresentValue As Double
    
            PresentValue = CDbl(InputBox("Enter the principal: ",
                                      "Watts A Loan?", "0.00"))
            Return PresentValue
        End Function
    
        Private Function GetInterestRate() As Double
            Dim Rate As Double
    
            Rate = CDbl(InputBox("Enter the interest rate: ",
                                      "Watts A Loan?", "0.00"))
            Return Rate
        End Function
    
        Private Function GetPeriod() As Integer
            Dim Months As Integer
    
            Months = CDbl(InputBox("Enter the number of months: ",
                                      "Watts A Loan?", "0.00"))
            Return Months
        End Function
    
        Private Sub ShowSummary(ByVal Principal As Double,
                                ByVal AnnualRate As Double,
                                ByVal Periods As Integer,
                                ByVal InterestCollected As Double,
                                ByVal TotalCollected As Double)
            MsgBox("Watts A Loan?" & vbCrLf &
                   "========================" & vbCrLf &
                   "Loan Summary" & vbCrLf &
                   "-------------------------------------" & vbCrLf &
                   "Principal:" & vbTab & vbTab & Principal.ToString("F") & vbCrLf &
                   "Interest Rate:" & vbTab & AnnualRate.ToString("P") & vbCrLf &
                   "Period:" & vbTab & vbTab & CStr(Periods * 12) & " months" & vbCrLf &
                   "Interest Amount:" & vbTab & InterestCollected.ToString("F") & vbCrLf &
                   "Future Value:" & vbTab & TotalCollected.ToString("F") & vbCrLf &
                   "========================",
                   MsgBoxStyle.OkOnly Or MsgBoxStyle.Information,
                   "Watts A Loan?")
        End Sub
    
        Public Function Main() As Integer
            Dim Principal As Double
            Dim InterestRate As Double
            Dim Period As Double
            Dim InterestAmount As Double
            Dim FutureValue As Double
    
            Announce()
            Principal = GetPrincipal()
            InterestRate = GetInterestRate() / 100
            Period = GetPeriod() / 12
    
            InterestAmount = Principal * InterestRate * Period
            FutureValue = Principal + InterestAmount
    
            ShowSummary(Principal, InterestRate, Period, InterestAmount, FutureValue)
            Return 0
        End Function
    
    End Module
  18. To debug, on the Standard toolbar, click the Step Into button Step Into
  19. To continue, press F8 four times
  20. Click OK on the message box
  21. Press F8 two times and notice the yellow margin button is positioned on Principal = GetPrincipal()
  22. Press F8 to start debugging the GetPrincipal() function
  23. Press F8 and notice that the debugging is continuing in the body of the GetPrincipal() function line by line
  24. When asked for the principal, type 21650 and press Enter
  25. Press F8 twice
  26. To stop the debugging, on the Standard toolbar, click the Stop Debugging button Stop Debugging
  27. To debug again, press F8 five times
  28. Click OK on the message box
  29. Click the Step Into button Step Into twice until the yellow margin button is positioned on the Principal = GetPrincipal() line
  30. To avoid debugging line after line in the GetPrincipal() function, on the main menu, click Debug -> Step Over
  31. When asked to give the principal, type 3600 and press Enter
  32. Click the Step Into button Step Into
  33. Keep pressing  the Step Over button Step Over
  34. When asked to provide the interest rate, type 14.05 and press Enter
  35. Continue stepping over
  36. When asked to provide the number of months, type 48 and press Enter
  37. Continue stepping over to the end
  38. On the main menu, click Debug -> Delete All Breakpoints
  39. On the main menu, click File -> Close Project or File -> Close Solution
  40. When asked whether you want to save, click Discard
 
 
   
 

Home Copyright © 2010 FunctionX, Inc.