Home

Error Handling

Introduction to Errors

Overview

There will be problems with your code or your application. Some problems will come from you, some problems will be caused by users, and some problems will be caused by neither you nor your users. This means that there are things you can fix, those you can avoid as much as possible, and there are situations beyond your control. Still, as much as you can, try anticipating any type of problem and take early action to avoid bad situations.

Practical Learning: Introducing Error Handling

  1. Start Microsoft Access
  2. In the list of files, click Business Mathematics from the previous lesson
  3. In the Navigation Pane, right-click Brokerage Company1 used in Lesson 14 and click Design View (or use the Brokerage Company2 form)
  4. On the form, right-click the Calculate button and click Build Event...

Error Categories

There are three main types of problems that you will deal with, directly or indirectly:

  1. Syntax: A syntax error comes from your mistyping a word or forming a bad expression in your code. It could be that you misspelled a keyword such as ByVel instead of ByVal. It could also be a bad expression such as 524+ + 62.55. It could be a "grammar" error such as providing the name of a variable before its data type when declaring a variable (quite common for those who regularly transition from different languages (C/C++, Pascal, C#, Java, F#))

    When you use Microsoft Visual Basic to write your code, it would point out the errors while you are writing your code, giving you time to fix them. When your database runs, it can let you know about other syntax errors. For this reason, syntax errors are almost the easiest to fix because, most of the time, the problem would be pointed out and you can fix it
  2. Run-Time: After all syntax errors have been fixed, the program may be ready for the user. There are different types of problems that a user may face when interacting with your database. Imagine that, in your code, you indicate that a picture would be loaded and displayed to the user but you forget to ship the picture or the directory of the picture indicated in your code becomes different when a user opens your database. This is a type of run-time error.
    Run-time errors are mostly easy to fix because you will know what problem is occurring and why
  3. Logic: These are errors that don't fit in any of the above categories. They could be caused by the user misusing your database, a problem with the computer on which the database is used while the same database is working fine in another computer. Because logic errors can be vague, they can also be difficult to fix

Handling Errors

Introduction

The Code Editor in Microsoft Visual Basic can help you detect syntax errors. For example, when a certain error occurs while you are writing your code, a message box would display, prompting you to fix the problem:

Error Detection

Error Detection

If there is a syntax error that that the Editor didn't signal or that you ignored when writing your code, you would find it out when the form or report is used.

A run-time error is one that occurs when using your application. Consider the following form:

Calculation

Private Sub cmdCalculate_Click()
    Dim Number#
    Dim Twice#
    
    Number = [txtNumber]
    Twice = Number * 2
    [txtResult] = Twice
End Sub

Here is an example of executing it:

Calculation

The first aspect you should take into consideration is to imagine what could cause a problem. If you think there is such a possibility, you can create a label that could be used to transfer code if a problem occurs.

Practical Learning: Introducing Errors

  1. Change the code as follows:
    Private Sub cmdCalculate_Click()
        Dim principal As Double, commission As Double
        Dim numberOfShares As Integer, pricePerShare As Double
    
        numberOfShares = CInt(Nz(txtNumberOfShares))
        pricePerShare = CDbl(Nz(txtPricePerShare))
    
        principal = numberOfShares * pricePerShare
    
        If principal = 0# Then
            commission = 0#
        End If
    
        If (principal > 0#) And (principal <= 2500#) Then
            commission = 26.25 + (principal * 0.0014)
        End If
            
        If (principal > 2500#) And (principal <= 6000#) Then
            commission = 45# + (principal * 0.0054)
        End If
            
        If (principal > 6000#) And (principal <= 20000#) Then
            commission = 60# + (principal * 0.0028)
        End If
            
        If (principal > 20000#) And (principal <= 50000#) Then
            commission = 75# + (principal * 0.001875)
        End If
            
        If (principal > 50000#) And (principal <= 500000#) Then
            commission = 131.25 + (principal * 0.0009)
        End If
            
        If (principal > 500000#) Then
            commission = 206.25 + (principal * 0.000075)
        End If
    
        txtPrincipal = FormatNumber(principal)
        txtCommission = FormatNumber(commission)
        txtTotalInvestment = FormatNumber(principal + commission)
        
    ThereWasAProblem:
        MsgBox "There was a problem when executing your instructions."
    End Sub
  2. Return to Microsoft Access and switch the form to Form View
  3. If you create a label as done in the above code, you should specify when to jump to that label. Otherwise, as in this case, the label section would always execute. To see this, click the Calculate button

    Introducing Error Handling

  4. Click OK on the message box
  5. Click Number of Shares and type 3822
  6. Click Price per Share and type 62.50
  7. Click the Calculate button

    Introducing Error Handling

  8. Click OK on the message box
  9. Return to Microsoft Visual Basic
  10. In this case, we want the label section to execute only when we want. To prevent the execution from reaching this section if not directed so, you can add an Exit Sub line above the label section. For an example, change the code as follows:
    Private Sub cmdCalculate_Click()
        Dim principal As Double, commission As Double
        Dim numberOfShares As Integer, pricePerShare As Double
    
        numberOfShares = CInt(Nz(txtNumberOfShares))
        pricePerShare = CDbl(Nz(txtPricePerShare))
    
        principal = numberOfShares * pricePerShare
    
        If principal = 0# Then
            commission = 0#
        End If
    
        If (principal > 0#) And (principal <= 2500#) Then
            commission = 26.25 + (principal * 0.0014)
        End If
            
        If (principal > 2500#) And (principal <= 6000#) Then
            commission = 45# + (principal * 0.0054)
        End If
            
        If (principal > 6000#) And (principal <= 20000#) Then
            commission = 60# + (principal * 0.0028)
        End If
            
        If (principal > 20000#) And (principal <= 50000#) Then
            commission = 75# + (principal * 0.001875)
        End If
            
        If (principal > 50000#) And (principal <= 500000#) Then
            commission = 131.25 + (principal * 0.0009)
        End If
            
        If (principal > 500000#) Then
            commission = 206.25 + (principal * 0.000075)
        End If
    
        txtPrincipal = FormatNumber(principal)
        txtCommission = FormatNumber(commission)
        txtTotalInvestment = FormatNumber(principal + commission)
        
        Exit Sub
        
    ThereWasAProblem:
        MsgBox "There was a problem when executing your instructions."
    End Sub
  11. Return to Microsoft Access
  12. Click Number of Shares and press Delete
  13. Click Price per Share and press Delete
  14. This time, if you use appropriate values, the label section would not be reached.
    Click the Calculate button

    Introducing Error Handling

  15. Click Number of Shares and type 5017
  16. Click Price per Share and type 35.80
  17. Click the Calculate button

    Introducing Error Handling

  18. Return to Microsoft Visual Basic

In Case Of Error, Jump To Label

The above code will work if the right value is provided. When you preview the form, imagine that the user types an inappropriate value such as 24$.58 instead of $24.58. In this case, the value is not a number. You would like the program to let the user know that there was a problem.

With some experience, you would know what the problem was, otherwise, you would face a vague explanation. If a problem occurs when a person is using your database, the computer may display an insignificant message. Therefore, you can start by creating an appropriate label as introduced above. An error normally occurs in a procedure. To make your code easier to read, you should create a label that shows that it is made for an error instead of being a regular label. The label should also reflect the name of the procedure. This is just a suggestion, not a rule.

Practical Learning: Jumping to a Label

  1. Change the label to cmdCalculate_Click_Error as follows:
    Private Sub cmdCalculate_Click()
        Dim principal As Double, commission As Double
        Dim numberOfShares As Integer, pricePerShare As Double
    
        numberOfShares = CInt(Nz(txtNumberOfShares))
        pricePerShare = CDbl(Nz(txtPricePerShare))
    
        principal = numberOfShares * pricePerShare
    
        If principal = 0# Then
            commission = 0#
        End If
    
        If (principal > 0#) And (principal <= 2500#) Then
            commission = 26.25 + (principal * 0.0014)
        End If
            
        If (principal > 2500#) And (principal <= 6000#) Then
            commission = 45# + (principal * 0.0054)
        End If
            
        If (principal > 6000#) And (principal <= 20000#) Then
            commission = 60# + (principal * 0.0028)
        End If
            
        If (principal > 20000#) And (principal <= 50000#) Then
            commission = 75# + (principal * 0.001875)
        End If
            
        If (principal > 50000#) And (principal <= 500000#) Then
            commission = 131.25 + (principal * 0.0009)
        End If
            
        If (principal > 500000#) Then
            commission = 206.25 + (principal * 0.000075)
        End If
    
        txtPrincipal = FormatNumber(principal)
        txtCommission = FormatNumber(commission)
        txtTotalInvestment = FormatNumber(principal + commission)
        
        Exit Sub
        
    cmdCalculate_Click_Error:
        MsgBox "There was a problem when executing your instructions."
    End Sub
  2. When you think there will be a problem in your code, somewhere in the lines under the name of the procedure but before the line that could cause the problem, type On Error GoTo followed by the name of the label that would deal with the error. For an example, change the code as follows:
    Private Sub cmdCalculate_Click()
        On Error GoTo cmdCalculate_Click_Error
        Dim principal As Double, commission As Double
        Dim numberOfShares As Integer, pricePerShare As Double
    
        numberOfShares = CInt(Nz(txtNumberOfShares))
        pricePerShare = CDbl(Nz(txtPricePerShare))
    
        principal = numberOfShares * pricePerShare
    
        If principal = 0# Then
            commission = 0#
        End If
    
        If (principal > 0#) And (principal <= 2500#) Then
            commission = 26.25 + (principal * 0.0014)
        End If
            
        If (principal > 2500#) And (principal <= 6000#) Then
            commission = 45# + (principal * 0.0054)
        End If
            
        If (principal > 6000#) And (principal <= 20000#) Then
            commission = 60# + (principal * 0.0028)
        End If
            
        If (principal > 20000#) And (principal <= 50000#) Then
            commission = 75# + (principal * 0.001875)
        End If
            
        If (principal > 50000#) And (principal <= 500000#) Then
            commission = 131.25 + (principal * 0.0009)
        End If
            
        If (principal > 500000#) Then
            commission = 206.25 + (principal * 0.000075)
        End If
    
        txtPrincipal = FormatNumber(principal)
        txtCommission = FormatNumber(commission)
        txtTotalInvestment = FormatNumber(principal + commission)
        
        Exit Sub
        
    cmdCalculate_Click_Error:
        MsgBox "There was a problem when executing your instructions."
    End Sub

    This informs the compiler that, if there is a problem when this code executes, jump to the indicated label. When the On Error GoTo statement is used, this indicates that if any type of error occurs while the code of this procedure executes, transfer the compilation to the label. In this case, as soon as something bad happens, the compiler marks the area where the problem occurred, skips the normal code and jumps to the label indicated by the On Error GoTo line. After the section of that label has executed, the compiler returns where the error occurred. If there is nothing to solve the problem, the compiler continues down but without executing the lines of code involved. In this case, it would encounter the Exit Sub line and get out of the procedure.

In Case Of Error, Jump To Line #

Although the label is more explicit, it only indicates to the compiler what line to jump to in case of a problem. The alternative is to specify a line number instead of a label.

Resume

If a problem occurs in your code and you provide a label to display a friendly message as done above, the compiler would display the message and exit from the procedure. If this happens, as mentioned above, when the compiler returns where the problem occurred, you can provide an alternative. For example, in our program, if the user provides an inappropriate value that causes the error, you can provide an alternate value and ask the compiler to continue as if nothing happened. In this case, you want to compiler to "resume" its activity.

To indicate that the program should continue, you can use the Resume keyword. Here is an example:

Private Sub cmdCalculate_Click()
    On Error GoTo cmdCalculate_Click_Error
    Dim Number#
    Dim Twice#
    
    Number = [txtNumber]
    
    Resume
    
    Twice = Number * 2
    [txtResult] = Twice
    
    Exit Sub
    
cmdCalculate_Click_Error:
    MsgBox "There was a problem when executing your instructions"
End Sub

When an error occurs, if you want the program to continue with an alternate value than the one that caused the problem, in the label section, type Resume Next.

Practical Learning: Resuming the Execution

  1. Change the code as follows:
    Private Sub cmdCalculate_Click()
        On Error GoTo cmdCalculate_Click_Error
        Dim principal As Double, commission As Double
        Dim numberOfShares As Integer, pricePerShare As Double
    
        numberOfShares = CInt(Nz(txtNumberOfShares))
        pricePerShare = CDbl(Nz(txtPricePerShare))
    
        principal = numberOfShares * pricePerShare
    
        If principal = 0# Then
            commission = 0#
        End If
    
        If (principal > 0#) And (principal <= 2500#) Then
            commission = 26.25 + (principal * 0.0014)
        End If
            
        If (principal > 2500#) And (principal <= 6000#) Then
            commission = 45# + (principal * 0.0054)
        End If
            
        If (principal > 6000#) And (principal <= 20000#) Then
            commission = 60# + (principal * 0.0028)
        End If
            
        If (principal > 20000#) And (principal <= 50000#) Then
            commission = 75# + (principal * 0.001875)
        End If
            
        If (principal > 50000#) And (principal <= 500000#) Then
            commission = 131.25 + (principal * 0.0009)
        End If
            
        If (principal > 500000#) Then
            commission = 206.25 + (principal * 0.000075)
        End If
    
        txtPrincipal = FormatNumber(principal)
        txtCommission = FormatNumber(commission)
        txtTotalInvestment = FormatNumber(principal + commission)
        
        Exit Sub
        
    cmdCalculate_Click_Error:
        MsgBox "There was a problem when executing your instructions."
        Resume Next
    End Sub
  2. In this case, since any numeric variable is initialized with 0, when the compiler returns to the line of code that caused the problem, it would use 0 as a substitute to the inappropriate value. Based on this, you can provide a new value to use in case of error. For an example, change the code as follows:
    Private Sub cmdCalculate_Click()
        On Error GoTo cmdCalculate_Click_Error
        Dim principal As Double, commission As Double
        Dim numberOfShares As Integer, pricePerShare As Double
    
        numberOfShares = CInt(Nz(txtNumberOfShares))
        pricePerShare = CDbl(Nz(txtPricePerShare))
    
        principal = numberOfShares * pricePerShare
    
        If principal = 0# Then
            commission = 0#
        End If
    
        If (principal > 0#) And (principal <= 2500#) Then
            commission = 26.25 + (principal * 0.0014)
        End If
            
        If (principal > 2500#) And (principal <= 6000#) Then
            commission = 45# + (principal * 0.0054)
        End If
            
        If (principal > 6000#) And (principal <= 20000#) Then
            commission = 60# + (principal * 0.0028)
        End If
            
        If (principal > 20000#) And (principal <= 50000#) Then
            commission = 75# + (principal * 0.001875)
        End If
            
        If (principal > 50000#) And (principal <= 500000#) Then
            commission = 131.25 + (principal * 0.0009)
        End If
            
        If (principal > 500000#) Then
            commission = 206.25 + (principal * 0.000075)
        End If
    
        txtPrincipal = FormatNumber(principal)
        txtCommission = FormatNumber(commission)
        txtTotalInvestment = FormatNumber(principal + commission)
        
        Exit Sub
        
    cmdCalculate_Click_Error:
        MsgBox "There was a problem when executing your instructions."
        numberOfShares = 0#
        pricePerShare = 0#
        Resume Next
    End Sub
  3. Return to Microsoft Access
  4. Click Number of Shares and press Delete
  5. Click Price per Share and press Delete
  6. This time, if you use inappropriate values, the form will respond rightly.
    Click the Calculate button

    Introducing Error Handling

  7. Click Number of Shares and type 7 thousands
  8. Click Calculate
  9. Click OK on the message box
  10. Click Price per Share and type 104$ and .35
  11. Click the Calculate button

    Introducing Error Handling

  12. Click OK on the message boxes
  13. Click Number of Shares and type 7136
  14. Click Price per Share and type 104.35
  15. Click Calculate

    Introducing Error Handling

  16. Save and close the form
  17. In the Navigation Pane, right-click Straight-Line Method1 accessed in Lesson 4 and continued in Lesson 9. Click Design View (or use the Straight-Line Method3 form)
  18. On the form, right-click the Calculate button and click Build Event...
  19. From what we learned above, change the event as follows:
    Private Sub cmdCalculate_Click()
    On Error GoTo cmdCalculate_Click_Error
    
        Dim cost
        Dim salvageValue
        Dim estimatedLife
        Dim depreciation
    
        cost = CDbl(Nz(txtCost))
        salvageValue = CDbl(Nz(txtSalvageValue))
        estimatedLife = CDbl(Nz(txtEstimatedLife))
    
        depreciation = SLN(cost, salvageValue, estimatedLife)
    
        txtDepreciation = FormatCurrency(depreciation)
    
        Exit Sub
        
    cmdCalculate_Click_Error:
        MsgBox "There seems to be a problem with the values you provided or something else caused this error.", _
               vbOKCancel Or vbInformation, "Business Mathematics - Depreciation"
               
        Resume Next
    End Sub

An Exit Label

To explicity indicate where a proedure should stop, create a label just above the Exit Sub line. By tradition, this label should use the name of the event followed by _Exit.

Practical Learning: Using an Exit Label

  1. To create an exit label, change the event as follows:
    Private Sub cmdCalculate_Click()
    On Error GoTo cmdCalculate_Click_Error
    
        Dim cost
        Dim salvageValue
        Dim estimatedLife
        Dim depreciation
    
        cost = CDbl(txtCost)
        salvageValue = CDbl(txtSalvageValue)
        estimatedLife = CDbl(txtEstimatedLife)
    
        depreciation = SLN(cost, salvageValue, estimatedLife)
    
        txtDepreciation = FormatCurrency(depreciation)
    
    cmdCalculate_Click_Exit:
        Exit Sub
        
    cmdCalculate_Click_Error:
        MsgBox "There seems to be a problem with the values you provided or something else caused this error.", _
               vbOKCancel Or vbInformation, "Business Mathematics - Depreciation"
        
        Resume Next
    End Sub
  2. After creating the exit label, on the last line of the error label section, create a line that includes the Resume keyword followed by the exit label. For an example, change the code as follows:
    Private Sub cmdCalculate_Click()
    On Error GoTo cmdCalculate_Click_Error
    
        Dim cost
        Dim salvageValue
        Dim estimatedLife
        Dim depreciation
    
        cost = CDbl(Nz(txtCost))
        salvageValue = CDbl(Nz(txtSalvageValue))
        estimatedLife = CDbl(Nz(txtEstimatedLife))
    
        depreciation = SLN(cost, salvageValue, estimatedLife)
    
        txtDepreciation = FormatCurrency(depreciation)
    
    cmdCalculate_Click_Exit:
        Exit Sub
        
    cmdCalculate_Click_Error:
        MsgBox "There seems to be a problem with the values you provided or something else caused this error.", _
               vbOKCancel Or vbInformation, "Business Mathematics - Depreciation"
    
        Resume cmdCalculate_Click_Exit
    End Sub
  3. Return to Microsoft Access and switch the form to Form View
  4. Click the Calculate button
  5. Click OK on the message box
  6. Click Asset Original Value and type a bad number such as 24$500
  7. Click Salvage Value and type a bad number such as 50;00
  8. Click Estimated Life and type a natural number such 8
  9. Click the Calculate button:

    Formatting a Currency Value

  10. Click the Calculate button
  11. Click Asset Original Value and change the number to a good one such as 24500
  12. Click Salvage Value and and change the number to a good one such as 5000
  13. Click the Calculate button:

    Formatting a Currency Value

  14. Close the form
  15. When asked whether you want to save, click No

The Err Object

Introduction

To support error handling, the Visual Basic language provides a class, or global object, named Err. This allows you to identify the error and its description. Because an error depends on what caused it and why, the values of the Err object also depend and are not always the same.

The Error Number

There ar different types of run-time errors that can occur when your database is used. When an error occurs, Microsoft Access displays a message box with the corresponding error number. Here is an example of a run-time error number 2489:

Error

To assist you with the errors, the Err class is equipped with a property named Number that allows you to identify an error by its number. The Number property is a constant integer. Most of the times, when a run-time error occurs, the above dialog box would show you the error number that occurred.

Practical Learning: Introducing the Err Object

  1. In the Navigation Pane, double-click Compound Interest1 (accessed in Lesson 14 or use the Compound Interest2 form)
  2. On the form, click the Calculate button
  3. On the Input Box, click OK

    Introducing the Err Object

  4. Click Principal and type 2500;00
  5. Click Interest Rate and type 735
  6. Click Periods and type 8
  7. Click the Calculate button

    Error

  8. On the message box, click End
  9. Click Principal and delete ;00
  10. Click Interest Rate and type 7&35
  11. Click Calculate
  12. On the message box, click End
  13. Click Interest Rate and type 7.35
  14. Click Calculate
  15. In the input box, type Daily and click OK
  16. On the message box, click End
  17. Click Periods and type 3;55
  18. Click the Calculate button
  19. If the user clicks Debug, the line that caused the error would be highlighted. For an example, on the message box, click Debug

    Error Detection

    Notice that, in the previous screen, we got the error number
  20. If you get an error number and know what it represents, you can write a conditional statement that isolate the error number and consequently you can display a message to the user. For an example, change the code as follows:
    Private Sub cmdCalculate_Click()
    On Error GoTo cmdCalculate_Click_Error
        Dim factor
        Dim principal
        Dim futureValue
        Dim interestRate
        Dim interestEarned
        Dim Periods As Integer
        Dim compounded As Integer
        Dim compoundFrequency As Integer
    
        principal = CDbl(Nz(txtPrincipal))
        interestRate = CDbl(Nz(txtInterestRate)) / 100#
        Periods = CInt(Nz(txtPeriods))
    
        compounded = CInt(InputBox("Enter a number for the desired compound frequency:" & vbCrLf & _
                                   "1 - Daily" & vbCrLf & _
                                   "2 - Weekly" & vbCrLf & _
                                   "3 - Monthly" & vbCrLf & _
                                   "4 - Quarterly" & vbCrLf & _
                                   "5 - Semiannually" & vbCrLf & _
                                   "6 - Anually", _
                                   "Compound interest", "1"))
        compoundFrequency = IIf(compounded = 1, 365, IIf(compounded = 2, 52, IIf(compounded = 3, 12, IIf(compounded = 4, 4, IIf(compounded = 5, 2, 1)))))
        factor = IIf(compounded = 1, interestRate / 365, _
                   IIf(compounded = 2, interestRate / 52, _
                     IIf(compounded = 3, interestRate / 12, _
                       IIf(compounded = 4, interestRate / 4, _
                         IIf(compounded = 5, interestRate / 2, interestRate) _
                       ) _
                     ) _
                   ) _
                 )
    
        futureValue = principal * ((1# + factor) ^ (Periods * compoundFrequency))
        interestEarned = futureValue - principal
    
        txtCompounded = IIf(compounded = 1, "Compounded Daily", _
                        IIf(compounded = 2, "Compounded Weekly", _
                        IIf(compounded = 3, "Compounded Monthly", _
                        IIf(compounded = 4, "Compounded Quarterly", _
                        IIf(compounded = 6, "Compounded Semi-Annually", _
                                            "Compounded Anually")))))
        txtInterestEarned = FormatNumber(interestEarned)
        txtFutureValue = FormatNumber(futureValue)
        
        Exit Sub
        
    cmdCalculate_Click_Error:
        If Err.Number = 13 Then
            MsgBox "Please provide a decimal number for the principal and the interest rate. " & _
                   "Also provide a natural number for the periods (as a number of years) and " & _
                   "type a natural number in the Input Box for the compound frequency.", _
                   VbMsgBoxStyle.vbOKOnly Or VbMsgBoxStyle.vbInformation, "Compound Interest"
        End If
    
        Resume Next
    End Sub
  21. Return to Microsoft Access
  22. Click the Calculate button:

    Introducing the Err Object

  23. Click OK on the message box
  24. In the Input Box, accept 1 and click OK
  25. Click Periods and type 3.55
  26. Click Calculate
  27. In the Input Box, type 3 and click OK

    Introducing the Err Object

  28. Save and close the form

The Error Message

Obviously an error number does not mean much. To indicate what each error number refers to, the Err class is equipped with a property named Description, which is a string. To display this message, you can create an On Error GoTo expression and indicate where to jump if an error occurs. Here is an example:

Private Sub cmdCalculate_Click()
    On Error GoTo cmbCalculate_Error
    Dim Number#
    Dim Twice#
    
    Number = [txtNumber]
    Twice = Number * 2
    [txtResult] = Twice
    
    Exit Sub
    
cmbCalculate_Error:
    MsgBox "Error Message: " & Err.Description
End Sub

This time, if the type of error you are anticipating occurs, you can rightfully display the description. Here is an example:

Calculation

Once again, notice that the type of message of the Err.Description string may not mean much to a regular user. For this reason, you should make it a habit to anticipate as many types of errors that may occur in your application and display more meaningful messages. You can do this in the section where the code would jump when an error occurs.

Practical Learning: Using the Error Message

The Source of the Error

It is assumed that an error would be caused when using your application. In fact, the database on which the user is working when the error occurred is considered as the source of the error. This information can be valuable at times. The application that caused an error is recognized as the Source property of the Err object. Most of the time, you will know this. Still, if you want to get this information, you can access the Source property of the Err object and get this as a string.

Debugging and the Immediate Window

The Immediate Window

Debugging consists of examining and testing portions of your code or parts of your database to identify problems that may occur whilee somebody is using your database. Microsoft Visual Basic provides as many tools as possible to assist you with this task.

The Immediate window is an object you can use to test functions and expressions. It is available in the Microsoft Visual Basic programming environment. To display the Immediate window, on the main menu of Microsoft Visual Basic, click View and click Immediate Window. It's a habit to keep the Immediate window in the bottom section of the Code Editor but you can move it from there by dragging its title bar:

The Immediate Window

Probably the simplest action you can perform in the Immediate window consists of testing an expression. For example, you can write an arithmetic operation and examine its result. To do this, in the Immediate window, type the question mark "?" followed by the expression and press Enter. Here is an example that tests the result of 275.85 + 88.26:

Immediate Window

One of the most basic actions you can perform in the Immediate window consists of testing a built-in function. To do this, type ? followed by the name of the function and its arguments, if any. Here is an example:

? UCase("République d'Afrique du Sud")

After typing the function and pressing Enter, the result would display in the next line:

Immediate Window

The Debug Object

The Immediate window is recognized in code as the Debug object. To programmatically display something, such as a string, in the Immediate window, the Debug object provides the Print method. The simplest way to use it consist of passing it a string. For example, imagine you create a button on a form, you name it cmdTestFullName and initialize it with a string. Here is an example of how you can display that string in the Immediate window:

Private Sub cmdTestFullName_Click()
    Dim strFullName$
    
    strFullName$ = "Daniel Ambassa"
    Debug.Print strFullName$
End Sub

When you click the button, the Immediate window would display the passed string:

Immediate Window

In the same way, you can create a more elaborate expression and test its value in the Immediate window:

Immediate Window

You can also pass a value, such as a date, that can easily be converted to a string.

Practical Learning: Ending the Lesson


Previous Copyright © 2005-2022, FunctionX, Inc. Next