Microsoft KB Archive/315965

= How to use structured exception handling in Visual Basic .NET or in Visual Basic 2005 =

Article ID: 315965

Article Last Modified on 12/6/2006

-

APPLIES TO


 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-



This article was previously published under Q315965



IN THIS TASK
SUMMARY Requirements Structured Exception Handling Catch an Exception Catch Multiple Exceptions Throw an Exception Complete Code Listing
 * Catch an Exception
 * Catch Multiple Exceptions
 * Throw an Exception

REFERENCES



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 &quot;On Error Goto&quot; 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 &quot;On Error Goto&quot; 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(&quot;A run-time error occurred&quot;) 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.</li>  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(&quot;Error: Divide by zero&quot;) Catch exc As OverflowException Console.WriteLine(&quot;Error: Overflow&quot;) 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. </li> On the Debug menu, click Start to run the application. The Console window displays the following error message:

<pre class="fixed_text">Error: Overflow

</li> Close the Console window.</li>  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(&quot;Error: &quot; & exc.Message) </li> On the File menu, click Close Solution.</li></ol>

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.</li> Create a new Console Application project in Visual Basic .NET or in Visual Basic 2005.</li> On the Project menu, click Add Class.</li> In the Add New Item window, type clsPerson.vb in the Name text box, and then click OK.</li>  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 (&quot;Age cannot be negative&quot;) 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. </li>  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 </li> On the Debug menu, click Start to run the application. The Console window displays the following error message:

<pre class="fixed_text">Age cannot be negative

</li> Close the Console window.</li></ol>

back to the top

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(&quot;A run-time error occurred&quot;) 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(&quot;Error: Divide by zero&quot;) Catch exc As OverflowException Console.WriteLine(&quot;Error: Overflow&quot;) Catch exc As Exception Console.WriteLine(&quot;Error: &quot; & 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(&quot;Age cannot be negative&quot;) End If   End Set End Property

End Class back to the top