A Review of .NET Exception Classes |
|
|
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.
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
Practical
Learning: Using the FormatException Class
|
|
- Start Microsoft Visual Basic if necessary.
Create a new Windows
Application named GeorgetownCleaningServices2
- 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 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
- In the Class Name combo box, select BtnTax
- 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
- In the Class Name combo box, select BtnDifference
- 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
- 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
- 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
- Execute the application and return to your programming environment
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:
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
Learning: Using an Argument Out Of Range Exception
|
|
- 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
- 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
- Execute the application.
- To test it enter valid and invalid values for the controls. Here
is an example:
- 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
|
|
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
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:
- Following the normal flow of the program, the compiler enters the
try block
- 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:
- The compiler gets out of the Try section
- 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
- 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
- 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
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:
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