- In unSEH, you have to remember to include On Error GoTo sometimes
in a random area inside the function. Besides On Error GoTo, you have
to remember to create a label section. The name of the label has to be
faithfully included in the On Error GoTo line
- When using the On Error GoTo technique, you have to make sure you
get out of the function at the right time, which is done using an Exit
Sub line. If you create this Exit Sub line in the wrong area in
your function, either the whole code would not be considered or an desired
section of the function would still execute, possibly producing an
unpredictable result. In the same way, a bizarre way of creating a Resume
or a Resume Next line would prevent the compiler from reaching or
considering some sections of a function
- As mentioned previously, the On Error GoTo system provides a
global variable named Err. As flexible as good intentioned as it may
appear, to effectively use Err, you have to proceed by trial and
error because Err identifies errors by a number but its documentation
does not possibly provide a list of error numbers. This is because Err
not only depends on the application (Visual Basic, VBA, etc) but also it
depends on the circumstance in which it is invoked. The only possible
solution is to cause an error in your code in order to cause Err to
show the numeric error that occurred. Then you have to use that error number
and create a custom error message
Because of these uncertainties, you should abandon the On
Error GoTo traditional error handling and use SEH in all of your new code.
Because SEH and unSEH techniques are inherently different, you cannot use both
in the same function.
|
Practical
Learning: Introducing Exception Handling
|
|
- Start Microsoft Visual Basic if necessary.
Create a new Windows Application named GeorgetownCleaningServices1
- Design the form as follows:
 |
| Control |
Name |
Text |
Additional Properties |
| Form |
|
|
Size: 378, 408 |
| Label |
|
Customer Name: |
|
| TextBox |
txtCustomerName1 |
|
|
| Label |
|
mm |
|
| Label |
|
dd |
|
| Label |
|
yyyy |
|
| Label |
|
Order Date: |
|
| TextBox |
txtMM |
1 |
|
| TextBox |
txtDD |
1 |
|
| TextBox |
txtYYYY |
2000 |
|
| Label |
|
Item Types |
|
| Label |
|
Qty |
|
| Label |
|
Unit Price |
|
| Label |
|
Sub-Total |
|
| Label |
|
Shirts |
|
| TextBox |
txtQtyShirts |
0 |
|
| TextBox |
txtUnitPriceShirts |
1.15 |
|
| TextBox |
txtSubTotalShirts |
0.00 |
|
| Label |
|
Pants |
|
| TextBox |
txtQtyPants |
0 |
|
| TextBox |
txtUnitPricePants |
1.95 |
|
| TextBox |
txtSubTotalPants |
0.00 |
|
| Label |
|
Other |
|
| TextBox |
txtQtyOther |
0 |
|
| TextBox |
txtUnitPriceOther |
3.50 |
|
| TextBox |
txtSubTotalOther |
0.00 |
|
| Button |
btnProcess |
Process |
|
| Label |
|
Customer Name: |
|
| TextBox |
txtCustomerName2 |
|
|
| Label |
|
Order date: |
|
| TextBox |
txtOrderDate |
|
|
| Label |
|
Tax Rate: |
|
| TextBox |
txtTaxRate |
5.75 |
|
| Label |
|
% |
|
| Button |
btnTax |
Tax |
|
| Label |
|
Total Order: |
|
| TextBox |
txtTotalOrder |
0.00 |
|
| Label |
|
Tax Amount: |
|
| TextBox |
txtTaxAmount |
0.00 |
|
| Label |
|
Net Price: |
|
| TextBox |
txtNetPrice |
0.00 |
|
| Label |
|
Amount Tended: |
|
| TextBox |
txtAmountTended |
0.00 |
|
| Button |
btnDifference |
Diff |
|
| Label |
|
Difference: |
|
| TextBox |
txtDifference |
0.00 |
|
|
- To arrange the tab sequence, on the main menu, click View -> Tab Order
- On the form, click only the following controls whose squares have a
white background, in the indicated order:

- Press Esc
- Right-click the form and click View Code
- Declare a few variables as follows:
Public Class Form1
' Order Information
Dim CustomerName As String
Dim mm As String
Dim dd As String
Dim yyyy As String
' Quantities of items
Dim NumberOfShirts As Integer
Dim NumberOfPants As Integer
Dim NumberOfOther As Integer
' Price of items
Dim PriceOneShirt As Double
Dim PriceAPairOfPants As Double
Dim PriceOther As Double
' Each of these sub totals will be used for cleaning items
Dim SubTotalShirts As Double
Dim SubTotalPants As Double
Dim SubTotalOther As Double
' Values used to process an order
Dim TaxRate As Double
Dim TotalOrder As Double
Dim TaxAmount As Double
Dim SalesTotal As Double
End Class
|
- In the Class Name combo box, select btnProcess
- In the Method Name, select Click and implement its event as follows:
Private Sub btnProcess_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnProcess.Click
If btnProcess.Text = "Process" Then
Height = 408
btnProcess.Text = "Reset"
Else
Height = 232
txtCustomerName1.Text = ""
txtMM.Text = "1"
txtDD.Text = "1"
txtYYYY.Text = "2000"
txtQtyShirts.Text = "0"
txtQtyPants.Text = "0"
txtQtyOther.Text = "0"
txtSubTotalShirts.Text = "0.00"
txtSubTotalPants.Text = "0.00"
txtSubTotalOther.Text = "0.00"
btnProcess.Text = "Process"
End If
' Request order information from the user
CustomerName = txtCustomerName1.Text
mm = txtMM.Text
dd = txtDD.Text
yyyy = txtYYYY.Text
' Request the quantity of each category of items
' Number of Shirts
NumberOfShirts = CInt(txtQtyShirts.Text)
' Number of Pants
NumberOfPants = CInt(txtQtyPants.Text)
' Number of Dresses
NumberOfOther = CInt(txtQtyOther.Text)
' Unit Prices of items
PriceOneShirt = CDbl(txtUnitPriceShirts.Text)
PriceAPairOfPants = CDbl(txtUnitPricePants.Text)
PriceOther = CDbl(txtUnitPriceOther.Text)
' Perform the necessary calculations
SubTotalShirts = NumberOfShirts * PriceOneShirt
SubTotalPants = NumberOfPants * PriceAPairOfPants
SubTotalOther = NumberOfOther * PriceOther
txtSubTotalShirts.Text = CStr(SubTotalShirts)
txtSubTotalPants.Text = CStr(SubTotalPants)
txtSubTotalOther.Text = CStr(SubTotalOther)
' Calculate the "temporary" total of the order
TotalOrder = SubTotalShirts + SubTotalPants + SubTotalOther
' Display the receipt
txtCustomerName2.Text = CustomerName
txtOrderDate.Text = mm + "/" & dd + "/" & yyyy
txtTotalOrder.Text = CStr(TotalOrder)
End Sub
|
- In the Class Name combo box, select btnTax
- In the Method Name, select Click and implement its event as follows:
Private Sub btnTax_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnTax.Click
' Get the tax rate
TaxRate = CDbl(txtTaxRate.Text) / 100
' Calculate the tax amount using a constant rate
TaxAmount = TotalOrder * TaxRate
' Add the tax amount to the total order
SalesTotal = TotalOrder + TaxAmount
txtTaxAmount.Text = TaxAmount.ToString()
txtNetPrice.Text = CStr(SalesTotal)
End Sub
|
- In the Class Name combo box, select btnDifference
- In the Method Name, select Click and implement its event as follows:
Private Sub btnDifference_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnDifference.Click
Dim AmountTended As Double = 0.0
Dim Difference As Double = 0.0
' Request money for the order
AmountTended = CDbl(txtAmountTended.Text)
' Calculate the difference owed to the customer
' or that the customer still owes to the store
Difference = AmountTended - SalesTotal
txtDifference.Text = CStr(Difference)
End Sub
|
- Return to the form and resize it form to appear as follows:

- To execute the application, on the Standard toolbar, click the Start
Without Debugging button
- Close the form and return to your programming environment
- Execute the application again. This time, type a letter such as d for
the quantity of shirts and click Process

- Click Quit to close the form and return to your programming environment
As mentioned already, errors are likely going to occur in
your program. The more you anticipate them and take action, the better your
application can be. We have already seen that syntax errors are usually human
mistakes such as misspelling, bad formulation of expressions, etc. The compiler
will usually help you fix the problem by pointing it out.
SEH is based on two main keywords: Try and Catch.
An exception handling section starts with the Try keyword and stops with
the End Try statement. Between Try and End Try, there must
by at least one Catch section. Therefore, exception handling uses the
following formula:
Try
' Code to execute in case everything is alright
Catch
' If something bad happened, deal with it here
End Try
Exception handling always starts with the Try
keyword. Under the Try line, Write the normal code that the compiler must
execute. Here is an example:
Private Sub CalculateClicked(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles btnCalculate.Click
Dim Number As Double
Dim Result As Double
Try
Number = CDbl(InputBox("Enter a number:"))
End Try
End Sub
As the compiler is treating code in the Try section,
if it encounters a problem, it "gets out" of the Try section and starts
looking for a Catch section. Therefore, you MUST always have a Catch
section. If you do not, the program will not compile. A Catch section
must be written before the End Try line:
Private Sub CalculateClicked(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles btnCalculate.Click
Dim Number As Double
Dim Result As Double
Try
Number = CDbl(InputBox("Enter a number:"))
Catch
End Try
End Sub
When the Catch keyword is simply written as above, it
would be asked to treat any error that occurs. For example, if you execute the
above code with a number such as 35$.75 instead of 35$.75, nothing would appear
to happen. This would indicate that the error was found and vaguely dealt with.
One problem in this case is that the compiler would not bother to let the user
know why there is no result displayed. Because there can be various types of
errors in a program, you also should make your program more intuitive and
friendlier so that, when an error occurs, the user would know the type of
problem. This is also useful if somebody calls you and says that your program is
not functioning right. If there is a way the user can tell you what exact type
of error is displaying, maybe you would find the solution faster.
|
Practical
Learning: Catching Exceptions
|
|
- To introduce exceptions, access the form's code and change the events of
the buttons as follows:
Public Class Form1
. . . No Change
Private Sub btnProcess_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnProcess.Click
. . . No Change
' Request the quantity of each category of items
' Number of Shirts
Try
NumberOfShirts = CInt(txtQtyShirts.Text)
Catch
End Try
' Number of Pants
Try
NumberOfPants = CInt(txtQtyPants.Text)
Catch
End Try
' Number of Dresses
Try
NumberOfOther = CInt(txtQtyOther.Text)
Catch
End Try
' Unit Prices of items
Try
PriceOneShirt = CDbl(txtUnitPriceShirts.Text)
Catch
End Try
Try
PriceAPairOfPants = CDbl(txtUnitPricePants.Text)
Catch
End Try
Try
PriceOther = CDbl(txtUnitPriceOther.Text)
Catch
End Try
. . . No Change
End Sub
Private Sub btnTax_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnTax.Click
' Get the tax rate
Try
TaxRate = CDbl(txtTaxRate.Text) / 100
Catch
End Try
' Calculate the tax amount using a constant rate
TaxAmount = TotalOrder * TaxRate
' Add the tax amount to the total order
SalesTotal = TotalOrder + TaxAmount
txtTaxAmount.Text = TaxAmount.ToString()
txtNetPrice.Text = SalesTotal.ToString()
End Sub
Private Sub btnDifference_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnDifference.Click
Dim AmountTended As Double = 0.0
Dim Difference As Double = 0.0
' Request money for the order
Try
AmountTended = CDbl(txtAmountTended.Text)
Catch
End Try
' Calculate the difference owed to the customer
' or that the customer still owes to the store
Difference = AmountTended - SalesTotal
txtDifference.Text = CStr(Difference)
End Sub
End Class
|
- Execute the application. This time, type invalid values in the quantity
text boxes and other text boxes where the user is supposed to enter some
values
- Click Process

- Return to your programming environment
As mentioned already, if an error occurs when processing the
program in the Try section, the compiler transfers the processing to the
next Catch section. You can then use the catch section to deal with the
error. At a minimum, you can display a message to inform the user. To do this,
you can create a message box in the Catch section. Here is an example:
Imports System.Drawing
Imports System.Windows.Forms
Module Exercise
Public Class Starter
Inherits Form
Private lblNumber As Label
Private txtNumber As TextBox
Friend WithEvents btnCalculate As Button
Private lblResult As Label
Private txtResult As TextBox
Dim components As System.ComponentModel.Container
Public Sub New()
InitializeComponent()
End Sub
Public Sub InitializeComponent()
Text = "Exception Behavior"
lblNumber = New Label
lblNumber.Location = New Point(17, 23)
lblNumber.Text = "Number:"
lblNumber.AutoSize = True
txtNumber = New TextBox
txtNumber.Location = New Point(78, 20)
txtNumber.Size = New Size(83, 20)
btnCalculate = New Button
btnCalculate.Location = New Point(78, 45)
btnCalculate.Text = "Calculate"
btnCalculate.Size = New Size(83, 23)
lblResult = New Label
lblResult.Location = New Point(17, 75)
lblResult.Text = "Result:"
lblResult.AutoSize = True
txtResult = New TextBox
txtResult.Location = New Point(76, 72)
txtResult.Size = New Size(83, 20)
Controls.Add(lblNumber)
Controls.Add(txtNumber)
Controls.Add(btnCalculate)
Controls.Add(lblResult)
Controls.Add(txtResult)
End Sub
Private Sub CalculateClicked(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles btnCalculate.Click
Dim Number As Double
Dim Result As Double
Try
Number = CDbl(txtNumber.Text)
Result = Number * 12.48
txtResult.Text = CStr(Result)
Catch
MsgBox("Something bad happened")
End Try
End Sub
End Class
Function Main() As Integer
Dim frmStart As Starter = New Starter
Application.Run(frmStart)
Return 0
End Function
End Module

Of course, your message may not be particularly clear but
this time, the program will not crash.
|
Practical
Learning: Displaying Custom Messages
|
|
- To display custom messages to the user, change the code as follows:
Public Class Form1
. . . No Change
Private Sub btnProcess_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnProcess.Click
. . . No Change
' Request the quantity of each category of items
' Number of Shirts
Try
NumberOfShirts = CInt(txtQtyShirts.Text)
Catch
MsgBox("The value you typed for the number of " & _
"shirts is not a valid number." & _
vbCrLf & "Please enter a natural number such " & _
"as 2 or 24 or even 248")
End Try
' Number of Pants
Try
NumberOfPants = CInt(txtQtyPants.Text)
Catch
MsgBox("The value you typed for the number of " & _
"pair or pants is not a valid number." & _
vbCrLf & "Please enter a natural number such " & _
"as 2 or 24 or even 248")
End Try
' Number of other items
Try
NumberOfOther = CInt(txtQtyOther.Text)
Catch
MsgBox("The value you typed for the number of " & _
"other items is not a valid number." & _
vbCrLf & "Please enter a natural number such " & _
"as 2 or 24 or even 248")
End Try
' Unit Prices of items
Try
PriceOneShirt = CDbl(txtUnitPriceShirts.Text)
Catch
MsgBox("The value you entered for the unit price " & _
"of a shirt is not a recognizable currency " & _
"amount." & vbCrLf & _
"Only natural or decimal numbers " & _
"are allowed. Please consult the management " & _
"to know the valid prices.")
End Try
Try
PriceAPairOfPants = CDbl(txtUnitPricePants.Text)
Catch
MsgBox("The value you entered for the unit price of " & _
"a pair of pants is not a recognizable " & _
"currency amount." & vbCrLf & _
"Only natural or decimal " & _
"numbers are allowed. You can consult the " & _
"management to find out about " & _
"the allowable prices.")
End Try
Try
PriceOther = CDbl(txtUnitPriceOther.Text)
Catch
MsgBox("The value you entered for the unit " & _
"price of other items is not a valid amount." & _
vbCrLf & "You must enter only a natural or a " & _
"decimal number. For more information, " & _
"please consult the management to get " & _
"the right prices.")
End Try
. . . No Change
End Sub
Private Sub btnTax_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnTax.Click
' Get the tax rate
Try
TaxRate = CDbl(txtTaxRate.Text) / 100
Catch
MsgBox("The value you entered is not " & _
"recognized as a valid tax rate." & _
vbCrLf & "A valid tax rate is a value " & _
"between 0 and 100.00" & _
vbCrLf & "Please try again.")
End Try
' Calculate the tax amount using a constant rate
TaxAmount = TotalOrder * TaxRate
' Add the tax amount to the total order
SalesTotal = TotalOrder + TaxAmount
txtTaxAmount.Text = TaxAmount.ToString()
txtNetPrice.Text = SalesTotal.ToString()
End Sub
Private Sub btnDifference_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles btnDifference.Click
Dim AmountTended As Double = 0.0
Dim Difference As Double = 0.0
' Request money for the order
Try
AmountTended = CDbl(txtAmountTended.Text)
Catch
MsgBox("The value you entered for the amount " & _
"tended is not valid. Only natural or " & _
"decimal numbers are allowed." & _
"Please try again.")
End Try
' Calculate the difference owed to the customer
' or that the customer still owes to the store
Difference = AmountTended - SalesTotal
txtDifference.Text = CStr(Difference)
End Sub
End Class
|
- Test the application with valid and invalid values. Here is an example:
- Return to Notepad
|
|