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

Article translations Article translations
Article ID: 315965 - View products that this article applies to.
This article was previously published under Q315965
Expand all | Collapse all

On This Page

SUMMARY

This article demonstrates how to use structured exception handling in Visual Basic .NET or in Visual Basic 2005.

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

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.

Catch an Exception

  1. Start Visual Studio .NET or Visual Studio 2005.
  2. Create a new Console Application project in Visual Basic .NET or in Visual Basic 2005.
  3. 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
    					
  4. 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
    						
  5. Close the Console window.

Catch Multiple Exceptions

This section demonstrates how to use multiple Catch statements to handle different errors.
  1. Open the Console Application project that you created in the previous section.
  2. 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.
  3. On the Debug menu, click Start to run the application. The Console window displays the following error message:
    Error: Overflow
    						
  4. Close the Console window.
  5. 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)
    					
  6. On the File menu, click Close Solution.

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.
  1. Start Visual Studio .NET or Visual Studio 2005.
  2. Create a new Console Application project in Visual Basic .NET or in Visual Basic 2005.
  3. On the Project menu, click Add Class.
  4. In the Add New Item window, type clsPerson.vb in the Name text box, and then click OK.
  5. 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.
  6. 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
    					
  7. On the Debug menu, click Start to run the application. The Console window displays the following error message:
    Age cannot be negative
    						
  8. Close the Console window.

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
				

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
				

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
				

REFERENCES

For more information, refer to the following Microsoft Web sites:
Error Handling the VB.NET Way: Living with Exceptions (a Visual Basic Developer article)
http://msdn.microsoft.com/en-us/library/aa227603(v=vs.60).aspx

How Do I Catch an Exception
http://msdn.microsoft.com/en-us/library/ys1b32h3(v=vs.80).aspx

How Do I Throw an Exception
http://msdn.microsoft.com/en-us/library/z7w9ff54(v=vs.80).aspx

Properties

Article ID: 315965 - Last Review: June 15, 2012 - Revision: 5.0
APPLIES TO
  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
Keywords: 
kbvs2005swept kbvs2005applies kbhowtomaster KB315965

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com