Home

Introduction to Exception Handling

  

Introduction

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 LearningPractical Learning: Introducing Exception Handling

  1. Start Microsoft Visual Studio and create a Console Application named GDCS4
  2. To create a new structure, on the main menu, click Project -> Add New Item...
  3. In the Templates list, click Code File
  4. Set the Name to OrderInfo
  5. Click Add
  6. 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
  7. To create a new file, on the main menu, click Project -> Add Class...
  8. Set the Name to OrderProcessing
  9. Click Add
  10. 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
  11. In the Solution Explorer, right-click Module1.vb and click Rename
  12. Type GeorgetownDryCleaningServices.vb and press Enter.
    If asked whether you want to rename the file, click Yes
  13. In the Solution Explorer, double-click GeorgetownDryCleaningServices.vb
  14. 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
  15. 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 . . .
  16. Close the DOS window and return to your programming environment

Try to Catch the Error

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 LearningPractical Learning: Trying Exceptions

  1. 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
  2. Save the file
 

 

 

Exceptions and Custom Messages

As mentioned already, if an error occurs when processing the program in the try section, the compiler transfer 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. Here is an example:

Public Class Exercise
    Public Function Main() As Integer
        Dim Number As Double

        Try
            Console.Write("Type a number: ")
            Number = cdbl(Console.ReadLine())

            Console.WriteLine(vbcrlf & "{0} * 2 = {1}", Number, Number * 2)
        Catch
            Console.WriteLine("There was a problem with the program")
        End Try

        Return 0
    Exit Function
End Class

Of course, this type of message is not particularly clear but this time, the program will not crash.

Practical LearningPractical Learning: Displaying Custom Messages

  1. To display custom messages to the user, change the OrderProcess.vb file as follows:
     
    Public Class OrderProcessing
    
        . . . No Change
    
        Public Sub ProcessOrder()
            
            . . . No Change
    
            ' Request the quantity of each category of items
            Try
                Console.Write("Number of Shirts:  ")
                order.NumberOfShirts = CInt(Console.ReadLine())
            Catch
                Console.WriteLine("The value you typed for the number of " & _
                      "shirts is not a valid number")
            End Try
    
            Try
                Console.Write("Number of Pants:   ")
                order.NumberOfPants = CInt(Console.ReadLine())
            Catch
                Console.WriteLine("The value you typed for the number of " & _
                              "pair or pants is not a valid number")
            End Try
    
            Try
                Console.Write("Number of Dresses: ")
                order.NumberOfDresses = CInt(Console.ReadLine())
            Catch
                Console.WriteLine("The value you typed for the number of " & _
                              "dresses is not a valid number")
            End Try
    
            ' 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
            Try
                Console.Write("Amount Tended? ")
                AmountTended = CDbl(Console.ReadLine())
            Catch
                Console.WriteLine( _
    		"You were asked to enter an amount of money but...")
            End Try
    
            ' 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()
            . . . No Change
        End Sub
    End Class
  2. Execute the application and enter the values when prompted. Here is an example:
     
    -/- Georgetown Cleaning Services -/-
    Enter Customer Name:  Alexandria
    Enter Customer Phone: (102) 797-8382
    Enter the order date(mm/dd/yyyy):  04/02/2001
    Enter the order time(hh:mm AM/PM): 09:22 AM
    Number of Shirts:  6
    Number of Pants:   W
    The value you typed for the number of pair or pants is not a valid number
    Number of Dresses: 5
    
    The Total order is: $30.09
    Amount Tended? _100D
    You were asked to enter an amount of money but...
    
    ====================================
    -/- Georgetown Cleaning Services -/-
    ====================================
    Customer:    Alexandria
    Home Phone:  (102) 797-8382
    Order Date:  Monday, April 02, 2001
    Order Time:  9:22 AM
    ------------------------------------
    Item Type  Qty Unit/Price Sub-Total
    ------------------------------------
    Shirts       6   0.95        5.70
    Pants        0   2.95           0
    Dresses      5   4.55       22.75
    ------------------------------------
    Total Order:   $28.45
    Tax Rate:      5.75 %
    Tax Amount:     $1.64
    Net Price:     $30.09
    ------------------------------------
    Amount Tended:  $0.00
    Difference:    ($30.09)
    ====================================
  3. Close the DOS window and return to your programming environment
 
 
   
 

Home Copyright © 2005-2016, FunctionX, Inc.