SUMMARY
This article demonstrates how to use structured exception handling in Visual Basic .NET or in Visual Basic 2005.
back to the top
Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
- Visual Basic .NET or Visual Basic 2005
This article assumes that you are familiar with the following topics:
- Visual Basic .NET or Visual Basic 2005
- Microsoft Visual Studio .NET or Microsoft Visual Studio 2005
back to the top
Structured Exception Handling
Visual Basic .NET or Visual Basic 2005 offers structured exception handling that provides a powerful, more readable alternative to "On Error Goto" error handling, which is available in previous versions of Microsoft Visual Basic. Structured exception handling is more powerful because it allows you to nest error handlers inside other error handlers within the same procedure. Furthermore, structured exception handling uses a block syntax similar to the
If...Else...End If statement. This makes Visual Basic .NET and Visual Basic 2005 code more readable and easier to maintain.
NOTE: Visual Basic .NET or Visual Basic 2005 retains the "On Error Goto" syntax for backward compatibility. You can still use this syntax in Visual Basic .NET or Visual Basic 2005 code. However, you cannot combine structured exception handling and
On Error statements within the same procedure. When you write new code, Microsoft recommends that you use structured exception handling.
The basic syntax of structured error handling is as follows:
Try
'Code that may raise an error.
Catch
'Code to handle the error.
Finally
'Code to do any final clean up.
End Try
The
Try and
End Try statements are required. The
Catch and
Finally statements are not required, though you must include at least one of them in your code. You can also specify multiple
Catch statements so that each
Catch block handles a specific error.
back to the top
Catch an Exception
- Start Visual Studio .NET or Visual Studio 2005.
- Create a new Console Application project in Visual Basic .NET or in Visual Basic 2005.
- In the Sub Main procedure, add the following code:
Dim a As Integer = 0
Dim b As Integer = 0
Dim c As Integer = 0
Try
a = b \ c
Catch exc As Exception
Console.WriteLine("A run-time error occurred")
Finally
Console.ReadLine()
End Try
- On the Debug menu, click Start to run the application. The code tries to divide a number by zero. This is an illegal operation that causes a divide by zero exception. Fortunately, the Catch block catches this error, and the Console window displays the following error message:
A run-time error has occurred
- Close the Console window.
back to the top
Catch Multiple Exceptions
This section demonstrates how to use multiple
Catch statements to handle different errors.
- Open the Console Application project that you created in the previous section.
- In the Sub Main procedure, replace the code that you copied in the previous section with the following code:
Dim a As Integer = 2147483647
Dim b As Integer = 0
Dim c As Integer = 0
Try
a += 1
Catch exc As DivideByZeroException
Console.WriteLine("Error: Divide by zero")
Catch exc As OverflowException
Console.WriteLine("Error: Overflow")
Finally
Console.ReadLine()
End Try
This code includes two Catch blocks: one to catch the previous divide by zero error, and one to catch the new overflow error. - On the Debug menu, click Start to run the application. The Console window displays the following error message:
- Close the Console window.
- Because you cannot always anticipate every error that may occur, you can add a Catch all block for unanticipated exceptions. For example, add the following code before the Finally statement to catch any unanticipated errors and display the appropriate error message:
Catch exc As Exception
Console.WriteLine("Error: " & exc.Message)
- On the File menu, click Close Solution.
back to the top
Throw an Exception
Structured exception handling uses the
Catch statement to catch an exception. Structured exception handling also provides a way to throw an exception. For example, it is useful to throw an exception when you perform data validation inside a
Property Set procedure because you may want to throw an error if a business rule is violated.
- Start Visual Studio .NET or Visual Studio 2005.
- Create a new Console Application project in Visual Basic .NET or in Visual Basic 2005.
- On the Project menu, click Add Class.
- In the Add New Item window, type clsPerson.vb in the Name text box, and then click OK.
- Add the following code inside the Public Class clsPerson...End Class statements:
Private mintAge As Integer
Public Property Age() As Integer
Get
Age = mintAge
End Get
Set(ByVal Value As Integer)
If Value >= 0 Then
mintAge = Value
Else
Throw New ArgumentException ("Age cannot be negative")
End If
End Set
End Property
This code creates an Age property. Because a person cannot have a negative age, an error is raised if the user of the class tries to set Age to a number that is less than zero. - In the Sub Main procedure of Module1.vb, add the following code:
Dim p As New clsPerson()
Try
p.Age = -1
Catch exc As Exception
Console.WriteLine(exc.Message)
Finally
Console.ReadLine()
End Try
- On the Debug menu, click Start to run the application. The Console window displays the following error message:
- Close the Console window.
back to the top
Complete Code Listing
Catch an Exception
Module Module1
Sub Main()
Dim a As Integer = 0
Dim b As Integer = 0
Dim c As Integer = 0
Try
a = b \ c
Catch exc As Exception
Console.WriteLine("A run-time error occurred")
Finally
Console.ReadLine()
End Try
End Sub
End Module
back to the top
Catch Multiple Exceptions
Module Module1
Sub Main()
Dim a As Integer = 2147483647
Dim b As Integer = 0
Dim c As Integer = 0
Try
a += 1
Catch exc As DivideByZeroException
Console.WriteLine("Error: Divide by zero")
Catch exc As OverflowException
Console.WriteLine("Error: Overflow")
Catch exc As Exception
Console.WriteLine("Error: " & exc.Message)
Finally
Console.ReadLine()
End Try
End Sub
End Module
back to the top
Throw an Exception
Module Module1
Sub Main()
Dim p As New clsPerson()
Try
p.Age = -1
Catch exc As Exception
Console.WriteLine(exc.Message)
Finally
Console.ReadLine()
End Try
End Sub
End Module
Public Class clsPerson
Private mintAge As Integer
Public Property Age() As Integer
Get
Age = mintAge
End Get
Set(ByVal Value As Integer)
If Value >= 0 Then
mintAge = Value
Else
Throw New ApplicationException("Age cannot be negative")
End If
End Set
End Property
End Class
back to the top
REFERENCES
For more information, refer to the following Microsoft Web sites:
back to the top