How to catch exceptions in Visual Basic 2005 or in Visual Basic .NET (301283)



The information in this article applies to:

  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

This article was previously published under Q301283
For a Microsoft Visual C# 2005 and Microsoft Visual C# .NET version of this article, see 308345.

For a Microsoft Visual Basic 6.0 version of this article, see 191474.

SUMMARY

Catching and dealing with exceptions is a standard programming task. This article demonstrates how to use a try-catch-finally block to catch an exception. A try-catch-finally block is a "wrapper" that you put around any code where the possibility of an exception exists.

A try-catch-finally block consists of the following sections:
  • Any code that may throw an exception is placed inside the try block.
  • If an exception is thrown, the catch block is entered, and the program can perform the appropriate operation to recover or alert the user.
  • The code in the finally block is always executed and can perform cleanup after an exception has occurred. The finally block is optional.

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows Server 2003, Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Microsoft Windows NT 4.0 Server
  • Microsoft Visual Basic 2005 or Microsoft Visual Basic .NET

Step-by-step example

  1. Create a new Console Application in Visual Basic 2005 or in Visual Basic .NET.
  2. In the Sub Main procedure, insert the code sample that follows. The sample declares and initializes three variables, wherein the initialization of "k" causes an error.
    ' This code generates an exception.
    	Console.WriteLine("We're going to divide 10 by 0 and see what happens...")
    	Console.WriteLine()
    
    	Dim i as Integer = 10
    	Dim j as Integer = 0
    	Dim k As Integer = i/j ' Error on this line.
    					
  3. Press the F5 key to view the exception.
  4. Wrap a try-catch statement around your code to capture the error. The following code catches all errors that are thrown in the code and displays a generic error message. Replace the code in the Sub Main procedure with the following code.
    ' This code shows how to catch an exception.
    Try
    	Console.WriteLine("We're going to divide 10 by 0 and see what happens...")
    	Console.WriteLine()
    
    	Dim i as Integer = 10
    	Dim j as Integer = 0
    	Dim k As Integer = i/j ' Error on this line. Control jumps to the catch block.
    Catch
    	Console.WriteLine("An error occurred.")
    End Try
  5. Press CTRL+F5 to run the project. Notice that the error message from the catch block is displayed.
  6. If some cleanup or post-processing needs to be done regardless of an error, use the finally part of the try-catch-finally statement. Code in the finally part of the statement is always executed, regardless of an exception. The following code displays "This statement is always printed" in the console, even if no error occurred. Replace the Sub Main code with the following code.
    ' This code shows how to catch an exception.	
    Try
    	Console.WriteLine("We're going to divide 10 by 0 and see what happens...")
    	Console.WriteLine()
    
    	Dim i as Integer = 10
    	Dim j as Integer = 0
    	Dim k As Integer k = i/j ' Error on this line. Control jumps to the catch block.
    
    Catch
    	Console.WriteLine("An error occurred.")
    Finally   ' This section is performed regardless of the above processing.
    	Console.WriteLine()
    	Console.WriteLine("This statement is always printed")
    End Try
    					
  7. Press CTRL+F5 to run the project.
  8. You can use the exception object with the catch statement to retrieve details about the exception. An exception has a number of properties that can help you identify help, source, or even stack information about an exception. This information can be very useful for tracking down the original cause of the exception or providing a better explanation of its source. The following sample catches an exception and gives a specific error message. As before, you can replace the code in the Sub Main procedure with the following code.

    Example 1
    ' This code shows how to catch an exception.
    Try
    	Console.WriteLine("We're going to divide 10 by 0 and see what happens...")
    	Console.WriteLine()
    
    	Dim i as Integer = 10
    	Dim j as Integer = 0
    	Dim k As Integer k = i/j ' Error on this line. Control jumps to the catch block.
    
    Catch e As Exception  ' Perform code that deals with the exception
                          ' or informs the user what occurred.
    	Console.WriteLine("The following error occurred:")
    	Console.WriteLine(e.ToString())  ' Print the error message to the user.
    
    Finally   ' This section is performed regardless of the above processing.
    	Console.WriteLine()
    	Console.WriteLine("This statement is always printed")
    End Try
    					
    Example 2
    ' This code shows how to catch an exception.
    Try
    	Console.WriteLine("We're going to divide 10 by 0 and see what happens...")
    	Console.WriteLine()
    
    	Dim i as Integer = 10
    	Dim j as Integer = 0
    	Dim k As Integer k = i/j ' Error on this line. Control jumps to the catch block.
    
    Catch e As Exception  ' Perform code that deals with the exception
                          ' or informs the user what occurred.
            Console.WriteLine("The following error occurred:")
            Console.WriteLine( e.Message )     ' Print the error message.
            Console.WriteLine( e.Source )      ' Name of application or object
                                               ' that caused the error
            Console.WriteLine( e.StackTrace )  ' String that contains the stack 
                                               ' trace for this exception
    Finally   ' This section is performed regardless of the above processing.
            Console.WriteLine()
            Console.WriteLine("This statement is always printed")
    End Try
    					
  9. Until this point, you have dealt with the particular case of a non-specific exception. However, if you know in advance what kind of exception is going to occur, you can catch the anticipated exception and process it accordingly. You can then use multiple Catch blocks to catch all other exceptions and deal with them as well. The following sample demonstrates this.
    Module Module1
    Sub Main()
    
    ' Attempt to do some file processing.
    ' This can cause a number of potential exceptions.
    ' Note that you can use the specific exceptions to get extra information about that exception,
    ' but this example focuses on showing control execution for those exceptions.
    
    Try
    	File.Create("c:/temp/test.txt")  ' Can fail for a number of reasons
    
    Catch ioe As System.IO.IOException ' This error may occur if the Temp folder does not exist.
    	Console.WriteLine("An IO error occurred. The c:\temp folder does not exist")
    
    Catch se As System.Security.SecurityException ' You do not have the appropriate permission
                                                  ' to take this action.
    	Console.WriteLine("You don't have the security permissions to take this action!")
    
    Catch e As Exception    ' Catch all other exceptions.
    	Console.WriteLine( e.ToString() )  ' Print the standard exception information.
    End Try
    End Sub
    End Module
    Because computer configurations may be different, the sample in this step may or may not throw an exception. If you want to force an IO exception, change the file path to a folder that does not exist on your computer.

REFERENCES

For more information, see the Microsoft .NET Framework Software Development Kit (SDK).

Modification Type:MinorLast Reviewed:10/3/2006
Keywords:kbvs2005swept kbvs2005applies kbHOWTOmaster KB301283 kbAudDeveloper