Home

.NET Framework Support for Exception Handling

 

A Review of .NET Exception Classes

 

Introduction

The .NET Framework provides various classes to handle almost any type of exception you can think of. There are so many of these classes that we can only mention a few.

There are two main ways you can use one of the classes of the .NET Framework. If you know for sure that a particular exception will be produced, pass its name to a Catch clause. Then, in the Catch section, display a custom message. The second option you have consists of using the Throw keyword. We will study it later.

In most cases, we will try to always indicate the type of exception that could be thrown if something goes wrong in a program.

The Format Exception

Everything the user types into an application using the keyboard is primarily a string and you must convert it to the appropriate type before using it. When you request a specific .NET type of value from the user, after the user has typed it and you decide to convert it to the appropriate type, if your conversion fails, the program produces (we will use he word "throw") an error. The error is of from the FormatException class.

Here is a program that deals with a FormatException exception:

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 = "Exceptional 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 = Double.Parse(TxtNumber.Text)
                Result = Number * 12.48
                TxtResult.Text = CStr(Result)
            Catch ex As FormatException
                MsgBox("Inavlid Value!")
            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

The FormatException exception

Practical LearningPractical Learning: Using the FormatException Class

  1. Start Microsoft Visual Basic if necessary.
    Create a new Windows Application named GeorgetownCleaningServices2
  2. 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  
  3. To arrange the tab sequence, on the main menu, click View -> Tab Order
  4. On the form, click only the following controls whose squares have a white background, in the indicated order:
     
    Georgetown Cleaning Services - Tab Order
  5. Press Esc
  6. Right-click the form and click View Code
  7. 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
  8. In the Class Name combo box, select BtnProcess
  9. In the Method Name, select Click and implement its event as follows:
    Private Sub BtnProcessClick(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
  10. In the Class Name combo box, select BtnTax
  11. In the Method Name, select Click and implement its event as follows:
    Private Sub BtnTaxClick(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
  12. In the Class Name combo box, select BtnDifference
  13. In the Method Name, select Click and implement its event as follows:
    Private Sub BtnDifferenceClick(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
  14. To display custom messages to the user, change the code as follows:
    Public Class Form1
    
        . . . No Change
    
        Private Sub BtnProcessClick(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 BtnTaxClick(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 BtnDifferenceClick(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
  15. To use the FormatException exception, change the code as follows:
    Public Class Form1
    
        . . . No Change
    
        Private Sub BtnProcessClick(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 ex As FormatException
                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 ex As FormatException
                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 ex As FormatException
                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 ex As FormatException
                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 ex As FormatException
                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 ex As FormatException
                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 BtnTaxClick(ByVal sender As Object, 
                                 ByVal e As System.EventArgs) 
                                 Handles BtnTax.Click
            ' Get the tax rate
            Try
                TaxRate = CDbl(TxtTaxRate.Text) / 100
            Catch ex As FormatException
                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 BtnDifferenceClick(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 ex As FormatException
                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
  16. Execute the application and return to your programming environment

The Overflow Exception

A computer application receives, processes, and produces values on a regular basis as the program is running. To better manage these values, as we saw when studying variables and data types, the compiler uses appropriate amounts of space to store its values. It is not unusual that either you the programmer or a user of your application provides a value that is beyond the allowed range based on the data type. For example, a byte uses 8 bits to store a value and a combination of 8 bits can store a number no more than 255. If you provide a value higher than 255 to be stored in a byte, you get an error. Consider the following program:

Private Sub CalculateClicked(ByVal sender As Object, 
                                     ByVal e As EventArgs) 
                                     Handles BtnCalculate.Click
            Dim Number As Byte
            Dim Result As Byte

            Try
                Number = Byte.Parse(TxtNumber.Text)
                Result = Number * 12
                TxtResult.Text = CStr(Result)
            Catch ex As FormatException
                MsgBox("Inavlid Value!")
            End Try
End Sub

When a value beyond the allowable range is asked to be stored in memory, the compiler produces (the verb is "throws" as we will learn soon) an error of the OverflowException class. Here is an example of running the program with a bad number:

Overflow

As with the other errors, when this exception is thrown, you should take appropriate action.

The Argument Out of Range Exception

Once again, in a .NET Framework application, a value is passed to the Parse() method of its data type for analysis. For a primitive data type, the Parse() method scans the string and if the converted value is beyond a determined range, the compiler throws an ArgumentOutOfRangeException exception.

Practical LearningPractical Learning: Using an Argument Out Of Range Exception

  1. Under the CustomerName variable, declare a variable named OrderTime of type DateTime
    Public Class Form1
    
        ' Order Information
        Dim CustomerName As String
        Dim OrderDate As DateTime
        Dim mm As String
        Dim dd As String
        Dim yyyy As String
  2. Change the Click event of the Process button as follows:
    Private Sub BtnProcessClick(ByVal sender As Object, 
                                     ByVal e As System.EventArgs) 
                                     Handles BtnProcess.Click
            . . . No Change
    
            ' Request order information from the user
            CustomerName = TxtCustomerName1.Text
    
            Try
                Dim mm As Integer, dd As Integer, yyyy As Integer
                mm = Integer.Parse(TxtMM.Text)
                dd = Integer.Parse(TxtDD.Text)
                yyyy = Integer.Parse(TxtYYYY.Text)
                OrderDate = New DateTime(yyyy, mm, dd)
    
            Catch ex As ArgumentOutOfRangeException
                MsgBox("The date you entered is not valid" & 
                                "- Please try again!")
            End Try
    
            . . . No Change
    
            ' Display the receipt
            TxtCustomerName2.Text = CustomerName
            TxtOrderDate.Text = FormatDateTime(OrderDate, DateFormat.LongDate)
            TxtTotalOrder.Text = CStr(TotalOrder)
    End Sub
  3. Execute the application.
  4. To test it enter valid and invalid values for the controls. Here is an example:

    Georgetown Cleaning Services - Wrong Date Value

  5. Close the form and return to your programming environment

The Divide By Zero Exception

Division by zero is an operation to always avoid. It is so important that it is one of the most fundamental exceptions of the computer. It is addressed at the core level even by the processors. It is also addressed by the operating systems at their level. It is also addressed by most, if not all, compilers. It is also addressed by most, if not, all libraries. This means that this exception is never welcomed anywhere. The .NET Framework also provides it own class to face this operation.

If an attempt to divide a value by 0, the compiler throws a DivideByZeroException exception.

Techniques of Using Exceptions

 

Throwing an Exception

As mentioned above, the Exception class is equipped with a Message property that carries a message for the error that occurred. We also mentioned that the message of this property may not be particularly useful to a user. Fortunately, you can create your own message and pass it to the Exception object. To be able to receive custom messages, the Exception class provides the following constructor:

Public Sub New(message As String)

To use it, in the section where you are anticipating the error, type the Throw keyword followed by a New instance of the Exception class using the constructor that takes a string. Here is an example:

Private Sub Button1Click(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles Button1.Click
        Dim Operand1 As Double
        Dim Operand2 As Double
        Dim Result As Double = 0.0
        Dim Oper As String = "."

        Try
            Operand1 = Double.Parse(TextBox1.Text)
            Oper = TextBox2.Text
            Operand2 = Double.Parse(TextBox3.Text)

            If (Oper <> "+") And 
               (Oper <> "-") And 
               (Oper <> "*") And 
               (Oper <> "/") Then
                Throw New Exception(Oper)
            End If

            Select Case Oper

                Case "+"
                    Result = Operand1 + Operand2

                Case "-"
                    Result = Operand1 - Operand2

                Case "*"
                    Result = Operand1 * Operand2

                Case "/"
                    Result = Operand1 / Operand2

                Case Else
                    MsgBox("Bad Operation")

            End Select

            TextBox4.Text = CStr(Result)
            
        Catch Ex As Exception
            MsgBox("Operation Error: " & Ex.Message & 
                   vbCrLf & Oper & " is not a valid operator")
        End Try
End Sub

Calculator 1: Exception Handling

Catching Various Exceptions

In the above examples, when we anticipated some type of problem, we instructed the compiler to use our default catch section. We left it up to the compiler to find out when there was a problem and we provided a catch section to deal with it. A method with numerous or complex operations and requests can also produce different types of errors. With such a type of program, you should be able to face different problems and deal with them individually, each by its own kind. To do this, you can create different catch sections, each made for a particular error. The formula used would be:

Try 
	' Code to Try
Catch Arg1

	' One Exception
Catch Arg2

	' Another Exception
End Try

The compiler would proceed in a top-down:

  1. Following the normal flow of the program, the compiler enters the try block
  2. If no exception occurs in the Try block, the rest of the Try block is executed
    If an exception occurs in the Try block, the compiler registers the type of error that occurred. If there is a Throw line, the compiler registers it also:
    1. The compiler gets out of the Try section
    2. The compiler examines the first Catch. If the first Catch matches the thrown error, that catch executes and the exception handling routine may seize. If the first Catch does not match the thrown error, the compiler proceeds with the next Catch
    3. The compiler checks the next match, if any, and proceeds as in the first match. This continues until the compiler finds a Catch clause that matches the thrown error
    4. If one of the catches matches the thrown error, its body executes. If no Catch matches the thrown error, the compiler calls the Exception class and uses the default message

Multiple catches are written if or when a try block is expected to throw different types of errors. For example, in our calculator, we want to consider only the addition, the subtraction, the multiplication, and the division. It is also likely that the user may type one or two invalid numbers. This leads us to know that our program can produce at least two types of errors at this time. Based on this, we can address them using two catch clauses as follows:

Private Sub Button1Click(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles Button1.Click
        Dim Operand1 As Double
        Dim Operand2 As Double
        Dim Result As Double = 0.0
        Dim Oper As String = "."

        Try
            Operand1 = Double.Parse(TextBox1.Text)
            Oper = TextBox2.Text
            Operand2 = Double.Parse(TextBox3.Text)

            If (Oper <> "+") And 
               (Oper <> "-") And 
               (Oper <> "*") And 
               (Oper <> "/") Then
                Throw New Exception(Oper)
            End If

            Select Case Oper

                Case "+"
                    Result = Operand1 + Operand2

                Case "-"
                    Result = Operand1 - Operand2

                Case "*"
                    Result = Operand1 * Operand2

                Case "/"
                    Result = Operand1 / Operand2

                Case Else
                    MsgBox("Bad Operation")

            End Select

            TextBox4.Text = CStr(Result)

        Catch ex As FormatException
            MsgBox("You type an invalid number. Please correct it")
        Catch Ex As Exception
            MsgBox("Operation Error: " & Ex.Message & 
                   vbCrLf & Oper & " is not a valid operator")
        End Try
End Sub

Catching multiple exceptions

This program works fine as long as the user types two valid numbers and a valid arithmetic operator. Anything else, such an invalid number or an unexpected operator would cause an error to be thrown:

Exception

 

Exceptions

Obviously various bad things could happen when this program is running. Imagine that the user wants to perform a division. You need to tell the compiler what to do if the user enters the denominator as 0 (or 0.00). If this happens, one of the options you should consider is to display a message and get out. Fortunately, the .NET Framework provides the DivideByZeroException class to deal with an exception caused by division by zero. As done with the message passed to the Exception class, you can compose your own message and pass it to the DivideByZeroException(string message) constructor.

Exception is the parent of all exception classes. It corresponds to the type of Catch that takes no argument. Therefore, if you write various catch blocks, the one that either takes nor argument or is of the Exception type must be the last.

Here is an example that catches two types of exceptions:

Private Sub Button1Click(ByVal sender As System.Object, 
                         ByVal e As System.EventArgs) 
                         Handles Button1.Click
    Dim Operand1 As Double
    Dim Operand2 As Double
    Dim Result As Double = 0.0
    Dim Oper As String = "."

    Try
        Operand1 = Double.Parse(TextBox1.Text)
        Oper = TextBox2.Text
        Operand2 = Double.Parse(TextBox3.Text)

        If (Oper <> "+") And 
           (Oper <> "-") And 
           (Oper <> "*") And 
           (Oper <> "/") Then
            Throw New Exception(Oper)
        End If

        Select Case Oper
            Case "+"
                Result = Operand1 + Operand2

            Case "-"
                Result = Operand1 - Operand2

            Case "*"
                Result = Operand1 * Operand2

            Case "/"
                If Operand2 = 0 Then
                   Throw New DivideByZeroException("Division by zero is not allowed")
                End If

                Result = Operand1 / Operand2

            Case Else
                MsgBox("Bad Operation")
        End Select

        TextBox4.Text = CStr(Result)

    Catch ex As FormatException
        MsgBox("You type an invalid number. Please correct it")
    Catch ex As DivideByZeroException
        MsgBox(ex.Message)
    Catch
        MsgBox("Invalid Operation: " & vbCrLf & Oper & " is not a valid operator")
    End Try
End Sub

Exception

 

Exception

 

Exception

 
 
 

Practical LearningPractical Learning: Identifying the Thrown Exception

  1. To catch various exceptions, change the code as follows:
    Public Class Form1
    
        ' Order Information
        Dim CustomerName As String
        Dim OrderDate As DateTime
        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
    
        Private Sub BtnProcessClick(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
    
            Try
                Dim mm As Integer, dd As Integer, yyyy As Integer
                mm = Integer.Parse(TxtMM.Text)
                dd = Integer.Parse(TxtDD.Text)
                yyyy = Integer.Parse(TxtYYYY.Text)
                OrderDate = New DateTime(yyyy, mm, dd)
    
                ' This exception is thrown if the user types a value that cannot
                ' be converted into a valid number
            Catch ex As FormatException
                MsgBox("Error: " & ex.Message & 
                        vbCrLf & "The value you entered " & 
                        "is not a valid number")
    
                ' This exception is thrown if the values that user had typed cannot
                ' produce a valid date value
            Catch ex As ArgumentOutOfRangeException
                MsgBox("The date you entered is not valid" & 
                                "- Please try again!")
            End Try
    
            ' Request the quantity of each category of items
            ' Number of Shirts
            Try
                NumberOfShirts = CInt(TxtQtyShirts.Text)
            Catch ex As FormatException
                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")
                ' This exception is thrown if the user types a negative value
            Catch Ex As OverflowException
                MsgBox("The number you typed is negative but " & 
                    "we cannot accept a negative number of shirts")
            End Try
    
            ' Number of Pants
            Try
                NumberOfPants = CInt(TxtQtyPants.Text)
            Catch ex As FormatException
                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")
            Catch Ex As OverflowException
                MsgBox("The number you typed is negative but " & 
                    "we cannot accept a negative number of shirts")
            End Try
    
            ' Number of other items
            Try
                NumberOfOther = CInt(TxtQtyOther.Text)
            Catch ex As FormatException
                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")
            Catch Ex As OverflowException
                MsgBox("The number you typed is negative but " & 
                    "we cannot accept a negative number of shirts")
            End Try
    
            ' Unit Prices of items
            Try
                PriceOneShirt = CDbl(TxtUnitPriceShirts.Text)
                If PriceOneShirt < 0 Then
                    Throw New Exception("Negative numbers are not allowed " & 
                                        "for the price of a shirt")
                End If
    
            Catch ex As FormatException
                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.")
            Catch Ex As Exception
                MsgBox("Something bad happened")
            End Try
    
            Try
                PriceAPairOfPants = CDbl(TxtUnitPricePants.Text)
                If PriceAPairOfPants < 0 Then
                    Throw New Exception("Negative numbers are not allowed " & 
                                        "for the price of a pair of pants")
                End If
    
            Catch ex As FormatException
                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.")
            Catch Ex As Exception
                MsgBox("Something bad happened")
            End Try
    
            Try
                PriceOther = CDbl(TxtUnitPriceOther.Text)
                If PriceOther < 0 Then
                    Throw New Exception("Negative numbers are " & 
                                        "not allowed for the price")
                End If
    
            Catch ex As FormatException
                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.")
            Catch Ex As Exception
                MsgBox("Something bad happened")
            End Try
    
            ' 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 = FormatDateTime(OrderDate, DateFormat.LongDate)
            TxtTotalOrder.Text = CStr(TotalOrder)
        End Sub
    
        Private Sub BtnTaxClick(ByVal sender As Object, 
                                 ByVal e As System.EventArgs) 
                                 Handles BtnTax.Click
            ' Get the tax rate
            Try
                TaxRate = CDbl(TxtTaxRate.Text) / 100
                If TaxRate < 0 Then
                    Throw New Exception("Negative numbers are not " & 
                                        "allowed for a tax rate")
                End If
    
            Catch ex As FormatException
                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.")
            Catch Ex As Exception
                MsgBox("Something bad happened")
            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 BtnDifferenceClick(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)
                If AmountTended < 0 Then
                    Throw New Exception("Negative numbers are not " & 
                                        "allowed forthe amount tended")
                End If
    
            Catch ex As FormatException
                MsgBox("The value you entered for the amount " & 
                       "tended is not valid. Only natural or " & 
                       "decimal numbers are allowed." & 
                       "Please try again.")
            Catch Ex As Exception
                MsgBox("Something bad happened")
            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
  2. Test the application and return to your programming environment

Exceptions Nesting

The calculator simulator we have studied so far performs a division as one of its assignments. We learned that, in order to perform any operation, the compiler must first make sure that the user has entered a valid operator. Provided the operator is one of those we are expecting, we also must make sure that the user typed valid numbers. Even if these two criteria are met, it is still possible that the user would enter 0 for the denominator. The block that is used to check for a non-zero denominator depends on the exception that validates the operators. The exception that could result from a zero denominator depends on the user first entering a valid number for the denominator.

You can create an exception inside of another. This is referred to as nesting an exception. This is done by applying the same techniques used to nest conditional statements. This means that you can write an exception that depends on, and is subject to, another exception. To nest an exception, create a Try clause in the body of the parent exception. The nested Try clause must be followed by its own Catch clause(s). To effectively handle the exception, make sure you include an appropriate Throw in the Try block. Here is an example:

Private Sub Button1Click(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles Button1.Click
        Dim Operand1 As Double
        Dim Operand2 As Double
        Dim Result As Double = 0.0
        Dim Oper As String = "."

        Try
            Operand1 = Double.Parse(TextBox1.Text)
            Oper = TextBox2.Text
            Operand2 = Double.Parse(TextBox3.Text)

            If (Oper <> "+") And 
               (Oper <> "-") And 
               (Oper <> "*") And 
               (Oper <> "/") Then
                Throw New Exception(Oper)
            End If

            Select Case Oper

                Case "+"
                    Result = Operand1 + Operand2
                    TextBox4.Text = CStr(Result)

                Case "-"
                    Result = Operand1 - Operand2
                    TextBox4.Text = CStr(Result)

                Case "*"
                    Result = Operand1 * Operand2
                    TextBox4.Text = CStr(Result)

                Case "/"
                    Try
                        If Operand2 = 0 Then
                   Throw New DivideByZeroException("Division by zero is not allowed")
                        End If
                        Result = Operand1 / Operand2

                    Catch ex As DivideByZeroException
                        MsgBox(ex.Message)
                    End Try

                Case Else
                    MsgBox("Bad Operation")

            End Select


        Catch ex As FormatException
            MsgBox("You type an invalid number. Please correct it")
        Catch
           MsgBox("Invalid Operation: " & vbCrLf & Oper & " is not a valid operator")
        End Try
End Sub

Exceptions and Functions

One of the most effective techniques used to deal with code is to isolate assignments in different functions. For example, the Select Case statement that was performing the operations in the "normal" version of our program could be written as follows:

Private Function Calculate(ByVal Value1 As Double, 
                               ByVal Value2 As Double, 
                               ByVal symbol As Char) As Double

        Dim Result As Double = 0.0

        Select Case symbol

            Case "+"
                Result = Value1 + Value2

            Case "-"
                Result = Value1 - Value2

            Case "*"
                Result = Value1 * Value2

            Case "/"
                Result = Value1 / Value2
        End Select

        Calculate = Result
End Function

Private Sub Button1Click(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles Button1.Click
        Dim Operand1 As Double
        Dim Operand2 As Double
        Dim Result As Double = 0.0
        Dim Oper As String = "."

        Try
            Operand1 = Double.Parse(TextBox1.Text)
            Oper = TextBox2.Text
            Operand2 = Double.Parse(TextBox3.Text)

            If (Oper <> "+") And 
               (Oper <> "-") And 
               (Oper <> "*") And 
               (Oper <> "/") Then
                Throw New Exception(Oper)
            End If

            If Oper = "/" Then
                If Operand2 = 0 Then
                   Throw New DivideByZeroException("Division by zero is not allowed")
                End If
            End If

            Result = Calculate(Operand1, Operand2, Oper)
            TextBox4.Text = CStr(Result)

        Catch ex As FormatException
            MsgBox("You type an invalid number. Please correct it")
        Catch ex As DivideByZeroException
            MsgBox(ex.Message)
        Catch
           MsgBox("Invalid Operation: " & vbCrLf & Oper & " is not a valid operator")
        End Try
End Sub

This is an example of running the program:

You can still use regular functions that handle exceptions and each function can handle its own exception(s). Here is an example:

Private Function Addition(ByVal Value1 As Double, 
                               ByVal Value2 As Double) As Double
        Addition = Value1 + Value2
End Function

Private Function Subtraction(ByVal Value1 As Double, 
                                 ByVal Value2 As Double) As Double
        Subtraction = Value1 - Value2
End Function

Private Function Multiplication(ByVal Value1 As Double, 
                                    ByVal Value2 As Double) As Double
        Multiplication = Value1 * Value2
End Function

Private Function Division(ByVal Value1 As Double, 
                              ByVal Value2 As Double) As Double

        Dim Result As Double = 0.0

        Try

            If Value2 = 0 Then
                Throw New DivideByZeroException("Division by zero is not allowed")
            End If

            Result = Value1 + Value2

        Catch ex As DivideByZeroException
            MsgBox(ex.Message)
        End Try

        Division = Result
End Function

Private Sub Button1Click(ByVal sender As System.Object, 
                              ByVal e As System.EventArgs) 
                              Handles Button1.Click
        Dim Operand1 As Double
        Dim Operand2 As Double
        Dim Result As Double = 0.0
        Dim Oper As String = "."

        Try
            Operand1 = Double.Parse(TextBox1.Text)
            Oper = TextBox2.Text
            Operand2 = Double.Parse(TextBox3.Text)

            If (Oper <> "+") And 
               (Oper <> "-") And 
               (Oper <> "*") And 
               (Oper <> "/") Then
                Throw New Exception(Oper)
            End If

            Select Case Oper

                Case "+"
                    Result = Addition(Operand1, Operand2)

                Case "-"
                    Result = Subtraction(Operand1, Operand2)

                Case "*"
                    Result = Multiplication(Operand1, Operand2)

                Case "/"
                    Result = Division(Operand1, Operand2)
            End Select

            TextBox4.Text = CStr(Result)

        Catch ex As FormatException
            MsgBox("You type an invalid number. Please correct it")
        Catch ex As DivideByZeroException
            MsgBox(ex.Message)
        Catch
           MsgBox("Invalid Operation: " & vbCrLf & Oper & " is not a valid operator")
        End Try
End Sub
 

Exercises

 

Geometric Calculations

  1. Create a Windows Application named GeometricCalculations
  2. Add a class named Sphere to the project. The class must be equipped with properties that can produce the diameter, the circumference, the area, and the volume
  3. Design the form so it can take a radius value and can display the diameter, the circumference, the area, and the volume
  4. Write code that can display the results of the diameter, the circumference, the area, and the volume calculated from the Sphere class
  5. Add the tooltips to all controls on the form
  6. Create a help file that  will assist the user with the application

Georgetown Cleaning Services

  1. Open the GeorgetownCleaningServices1 application from the previous lesson
  2. Add the tooltips to all controls on the form
  3. Create a help file that  will assist the user with the application

Clarksville Ice Cream

  1. Create a Windows Application named ClarskvilleIceCream1a
  2. Design the form as follows:
     
  3. Add tool tips and help to the application
 
 
   
 

Home Copyright © 2010-2012 FunctionX