|
|
Title | Use try catch blocks to protect against unexpected errors in Visual Basic .NET |
Description | This example shows how to use try catch blocks to protect against unexpected errors in Visual Basic .NET. |
Keywords | syntax, try, try catch, error handlings, bugs, Visual Basic .NET, VB.NET |
Categories | Software Engineering |
|
|
Most programs cannot anticipate every possible error. You can watch for things like missing files but it's hard to stop a determined user from entering "ten" in a TextBox that should contain a number. (Actually you can prevent that by using a NumericUpDown, Slider, ComboBox, or other control instead of a TextBox, but those controls don't work well if the user must enter values that span a huge range.)
In cases where you cannot predict all possible errors, you can use a try catch block. Place the code that could fail inside the try part. Then use one or more catch sections to handle any errors that occur. An optional exception variable can gather information about the error for your catch code to use in determining what went wrong and what you should do about it.
In this program, when you enter two integers X and Y and click the Calculate button, the program divides X by Y. Enter the value "ten" to cause a formatting error. Enter 0 for Y to cause a divide by zero error.
The following code shows how the program performs the calculation.
|
|
' Perform the calculation.
Private Sub btnCalculate_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnCalculate.Click
' Clear the result (in case the calculation fails).
txtResult.Clear()
Try
' Perform the operations that might fail.
Dim x As Integer = Integer.Parse(txtX.Text)
Dim y As Integer = Integer.Parse(txtY.Text)
Dim result As Integer = x / y
txtResult.Text = result.ToString()
Catch fmt_ex As FormatException
' A formatting error occurred.
' Report the error to the user.
MessageBox.Show( _
"The input values must be integers.", _
"Invalid Input Values", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As Exception
' Some other error occurred.
' Report the error to the user.
MessageBox.Show(ex.Message, "Calculation Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
' Record the kind of exception class so we can
' catch it specifically.
Console.WriteLine(ex.GetType().Name)
Finally
MessageBox.Show("Done", "Done", _
MessageBoxButtons.OK, _
MessageBoxIcon.Information)
End Try
End Sub
|
|
|
|
|
|