Exception Handling in Visual Basic .NET
Last Updated: May 24, 2021
We will first see the following code and run the program first. Here I am going to divide two numbers and show the results in a Label.
This the code for click event handler of the Button
Public Class Form1 Private Sub ButtonDivide_Click(sender As Object, e As EventArgs) Handles ButtonDivide.Click Dim number1 As Double Dim number2 As Double Dim result As Double number1 = CType(TextBoxNumber1.Text, Double) number2 = CType(TextBoxNumber2.Text, Double) result = number1 / number2 LabelResult.Text = result End Sub End Class
Leave the TextBoxes blank and You click the Button.
What will be the error you can see?
So you will get an error called InvalidCastException
. Because you are casting blank space to Double
data type
So I will add Try… Catch statement to handle it and show an error message to the user
Public Class Form1 Private Sub ButtonDivide_Click(sender As Object, e As EventArgs) Handles ButtonDivide.Click Dim number1 As Double Dim number2 As Double Dim result As Double Try number1 = CType(TextBoxNumber1.Text, Double) number2 = CType(TextBoxNumber2.Text, Double) result = number1 / number2 LabelResult.Text = result Catch Err As InvalidCastException MessageBox.Show(Err.Message) End Try End Sub End Class
Now you will get MessageBox with message Conversion from String “” to type Double is not valid
Using the Catch statement I caught the Exception and I showed a custom error message to the user without terminating the project