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
Error Categories
There are three main types of problems that you will deal with, directly or indirectly:
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:
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:
Private Sub cmdCalculate_Click() Dim Number# Dim Twice# Number = [txtNumber] Twice = Number * 2 [txtResult] = Twice End Sub
Here is an example of executing it:
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
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
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
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
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
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.
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
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
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
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
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
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
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:
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
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
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:
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
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:
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:
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:
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:
In the same way, you can create a more elaborate expression and test its value in the 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 |
|