|
Introduction to Exception Handling
|
|
|
As opposed to error
handling techniques used to deal
with a program's problems, the Visual Basic language now supports a technique referred to as exception
handling. This technique was mostly used by other languages such as C/C++,
Object Pascal, C#, etc. This technique is also referred to as structured
exception handling (SEH).
|
Practical Learning: Introducing Exception Handling |
|
- Start Microsoft Visual Studio and create a Console Application named GDCS4
- To create a new structure, on the main menu, click Project -> Add New
Item...
- In the Templates list, click Code File
- Set the Name to
OrderInfo
- Click Add
- In the document, type the following:
Public Structure OrderInformation
' Basic information about an order
Public CustomerName As String
Public HomePhone As String
Public OrderDate As DateTime
Public OrderTime As DateTime
Public NumberOfShirts As Integer
Public NumberOfPants As Integer
Public NumberOfDresses As Integer
End Structure
|
- To create a new file, on the main menu, click Project -> Add Class...
- Set the Name to OrderProcessing
- Click Add
- Change the document as follows:
Public Class OrderProcessing
' Price of items
ReadOnly PriceOneShirt As Double = 0.95
ReadOnly PriceAPairOfPants As Double = 2.95
ReadOnly PriceOneDress As Double = 4.55
ReadOnly TaxRate As Double = 0.0575 ' 5.75%
Dim order As OrderInformation
' Each of these sub totals will be used for cleaning items
Private SubTotalShirts As Double
Private SubTotalPants As Double
Private SubTotalDresses As Double
' Values used to process an order
Private TotalOrder As Double
Private TaxAmount As Double
Private SalesTotal As Double
Private AmountTended As Double
Private Difference As Double
Public Sub ProcessOrder()
Console.WriteLine("-/- Georgetown Cleaning Services -/-")
' Request order information from the user
Console.Write("Enter Customer Name: ")
Order.CustomerName = Console.ReadLine()
Console.Write("Enter Customer Phone: ")
Order.HomePhone = Console.ReadLine()
Console.Write("Enter the order date(mm/dd/yyyy): ")
Order.OrderDate = DateTime.Parse(Console.ReadLine())
Console.Write("Enter the order time(hh:mm AM/PM): ")
Order.OrderTime = DateTime.Parse(Console.ReadLine())
' Request the quantity of each category of items
Console.Write("Number of Shirts: ")
order.NumberOfShirts = CInt(Console.ReadLine())
Console.Write("Number of Pants: ")
order.NumberOfPants = CInt(Console.ReadLine())
Console.Write("Number of Dresses: ")
order.NumberOfDresses = CInt(Console.ReadLine())
' Perform the necessary calculations
SubTotalShirts = Order.NumberOfShirts * PriceOneShirt
SubTotalPants = Order.NumberOfPants * PriceAPairOfPants
SubTotalDresses = Order.NumberOfDresses * PriceOneDress
' Calculate the "temporary" total of the order
TotalOrder = SubTotalShirts + SubTotalPants + SubTotalDresses
' Calculate the tax amount using a constant rate
TaxAmount = TotalOrder * TaxRate
' Add the tax amount to the total order
SalesTotal = TotalOrder + TaxAmount
' Communicate the total to the user...
Console.WriteLine(vbcrlf & "The Total order is: {0:C}", SalesTotal)
' and request money for the order
Console.Write("Amount Tended? ")
AmountTended = Decimal.Parse(Console.ReadLine())
' Calculate the difference owed to the customer
' or that the customer still owes to the store
Difference = AmountTended - SalesTotal
ShowReceipt()
End Sub
Private Sub ShowReceipt()
Console.WriteLine()
' Display the receipt
Console.WriteLine("====================================")
Console.WriteLine("-/- Georgetown Cleaning Services -/-")
Console.WriteLine("====================================")
Console.WriteLine("Customer: {0}", Order.CustomerName)
Console.WriteLine("Home Phone: {0}", Order.HomePhone)
Console.WriteLine("Order Date: {0:D}", Order.OrderDate)
Console.WriteLine("Order Time: {0:t}", Order.OrderTime)
Console.WriteLine("------------------------------------")
Console.WriteLine("Item Type Qty Unit/Price Sub-Total")
Console.WriteLine("------------------------------------")
Console.WriteLine("Shirts {0,3} {1,4} {2,6}", _
order.NumberOfShirts, PriceOneShirt, SubTotalShirts)
Console.WriteLine("Pants {0,3} {1,4} {2,6}", _
order.NumberOfPants, PriceAPairOfPants, SubTotalPants)
Console.WriteLine("Dresses {0,3} {1,4} {2,6}", _
order.NumberOfDresses, PriceOneDress, SubTotalDresses)
Console.WriteLine("------------------------------------")
Console.WriteLine("Total Order: {0,6}", TotalOrder.ToString("C"))
Console.WriteLine("Tax Rate: {0,6}", TaxRate.ToString("P"))
Console.WriteLine("Tax Amount: {0,6}", TaxAmount.ToString("C"))
Console.WriteLine("Net Price: {0,6}", SalesTotal.ToString("C"))
Console.WriteLine("------------------------------------")
Console.WriteLine("Amount Tended: {0,6}", AmountTended.ToString("C"))
Console.WriteLine("Difference: {0,6}", Difference.ToString("C"))
Console.WriteLine("====================================")
End Sub
End Class
|
- In the Solution Explorer, right-click Module1.vb and click Rename
- Type GeorgetownDryCleaningServices.vb and press Enter.
If asked whether you want to rename the file, click Yes
- In the Solution Explorer, double-click GeorgetownDryCleaningServices.vb
- Change the file as follows:
Module GeorgetownDryCleaningServices
Public Function Main() As Integer
Dim Order As OrderProcessing = New OrderProcessing
Order.ProcessOrder()
Return 0
End Function
End Module
|
- Press Ctrl + F5 to execute the application. Here is an example:
-/- Georgetown Cleaning Services -/-
Enter Customer Name: Judith Pearson
Enter Customer Phone: (301) 884-0912
Enter the order date(mm/dd/yyyy): 10/05/2009
Enter the order time(hh:mm AM/PM): 08:12
Number of Shirts: 6
Number of Pants: 4
Number of Dresses: 1
The Total order is: $23.32
Amount Tended? 25
====================================
-/- Georgetown Cleaning Services -/-
====================================
Customer: Judith Pearson
Home Phone: (301) 884-0912
Order Date: Monday, October 05, 2009
Order Time: 8:12 AM
------------------------------------
Item Type Qty Unit/Price Sub-Total
------------------------------------
Shirts 6 0.95 5.7
Pants 4 2.95 11.8
Dresses 1 4.55 4.55
------------------------------------
Total Order: $22.05
Tax Rate: 5.75 %
Tax Amount: $1.27
Net Price: $23.32
------------------------------------
Amount Tended: $25.00
Difference: $1.68
====================================
Press any key to continue . . .
|
- Close the DOS window
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 will 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
Catch
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:
Module Exercise
Public Function Main() As Integer
Dim Number As Double
Dim Twice As Double
Try
Console.Write("Enter a number: ")
Number = Console.ReadLine()
Twice = Number * 2
Console.WriteLine("{0} * 2 = {1}", Number, Twice)
Console.WriteLine()
End Try
Return 0
Exit Function
End Module
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 don't, as seen on the above code, the
program will not compile. A Catch section must be written before
the End Try line:
Module Exercise
Public Function Main() As Integer
Dim Number As Double
Dim Twice As Double
Try
Console.Write("Enter a number: ")
Number = Console.ReadLine()
Twice = Number * 2
Console.WriteLine("{0} * 2 = {1}", Number, Twice)
Console.WriteLine()
Catch
End Try
Return 0
Exit Function
End Module
When the Catch keyword is simply written as above, it
would be asked to treat any error that occurs. For example, here is one
example of executing the above program:
Enter a number: 244.58
244.58 * 2 = 489.16
Here is another example of executing the same program:
Enter a number: 24$.58
Notice that the program stops if there is any type of
problem but in this case, it doesn't 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 a problem 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 what exact type of
error is displaying, may be you would find the solution faster.
Practical
Learning: Trying Exceptions |
|
- To introduce exceptions, access the OrderProcessing.vb file and change it as
follows:
Public Class OrderProcessing
. . . No Change
Public Sub ProcessOrder()
Console.WriteLine("-/- Georgetown Cleaning Services -/-")
' Request order information from the user
. . . No Change
' Request the quantity of each category of items
Try
Console.Write("Number of Shirts: ")
order.NumberOfShirts = CInt(Console.ReadLine())
Catch
End Try
Try
Console.Write("Number of Pants: ")
order.NumberOfPants = CInt(Console.ReadLine())
Catch
End Try
Try
Console.Write("Number of Dresses: ")
order.NumberOfDresses = CInt(Console.ReadLine())
Catch
End Try
. . . No Change
End Sub
Private Sub ShowReceipt()
. . . No Change
End Sub
End Class
|
- Save the file
|
|