How to catch exceptions in Visual C#

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

On This Page

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 are required:
  • Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows NT 4.0 Server
  • Microsoft Visual C# .NET or Microsoft Visual C# 2005

How to Catch Exceptions in Visual C#

  1. Create a new Console Application in Visual C#.

    Note In Visual C# 2005, Program.cs is created by default instead of Class1.cs.
  2. Replace all of the code in the Class1 code window with the following sample code. The code declares and initializes three variables, wherein the initialization of "k" causes an error.
    // This code generates an exception.
    using System;
    
    namespace ExceptionApp
    {
        class Class1
        {
    	static void Main()
    	{
                Console.WriteLine("We're going to divide 10 by 0 and see what happens...") ;
                Console.WriteLine() ;
    	   int i = 10 ;
                int j = 0 ;
                int k = i/j ; // Error on this line. 
    	}
        }
    }
    					
  3. Press F5. You receive a System.DivideByZeroException 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 Class1 code window with the following:
    // This code shows how to catch an exception.
    using System;
    
    namespace ExceptionApp
    {
        class Class1
        {
    	static void Main()
    	{
                try
                {
                    Console.WriteLine("We're going to divide 10 by 0 and see what happens...") ;
                    Console.WriteLine() ;
    	       int i = 10 ;
                    int j = 0 ;
                    int k = i/j ; // Error on this line.
                }
                catch
                {
                    Console.WriteLine("An error occurred.");
                }
    	}
        }
    }
    
    					
  5. Press CTRL+F5 to run the application. Note that the error message from the catch block is displayed, rather than the system exception message.
  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 code in the Class1 code window with the following:
    // This code shows how to catch an exception.
    using System;
    
    namespace ExceptionApp
    {
        class Class1
        {
    	static void Main()
    	{
                try
                {
                    Console.WriteLine("We're going to divide 10 by 0 and see what happens...") ;
                    Console.WriteLine() ;
    	       int i = 10 ;
                    int j = 0 ;
                    int k = i/j ; // Error on this line.
                }
                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");   
                }
    	}
        }
    }
    					
  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 the 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 Class1 code window with the following code:
    // This code shows how to catch an exception.
    using System;
    
    namespace ExceptionApp
    {
        class Class1
        {
    	static void Main()
    	{
                try
                {
                    Console.WriteLine("We're going to divide 10 by 0 and see what happens...") ;
                    Console.WriteLine() ;
    	       int i = 10 ;
                    int j = 0 ;
                    int k = i/j ; // Error on this line.
                }
                catch(Exception e)
                {
                    Console.WriteLine("An error occurred.");
                    Console.WriteLine(e.ToString());
                }
                finally   //This section is performed regardless of the above processing.
                {
                    Console.WriteLine();
                    Console.WriteLine("This statement is always printed");   
                }
    	}
        }
    }
    					
    The following code sample demonstrates how to obtain extended error information. This sample provides the message, the source of the error, and the stack trace:
    // This code shows how to catch an exception.
    using System;
    
    namespace ExceptionApp
    {
        class Class1
        {
    	static void Main()
    	{
                try
                {
                    Console.WriteLine("We're going to divide 10 by 0 and see what happens...") ;
                    Console.WriteLine() ;
    	       int i = 10 ;
                    int j = 0 ;
                    int k = i/j ; // Error on this line. Control jumps to the catch block.
                }
                //Perform code that deals with the exception or inform the user what occurred.
                catch(Exception e)  
                {
                    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");   
                }
    	}
        }
    }
    					
  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:
    // This code shows how to catch an exception.
    using System;
    using System.IO;
    using System.Security;
    
    namespace ExceptionApp
    {
        class Class1
        {
    	static void Main()
    	{
    	    try
    	    {
    		File.Create("c:\\temp\\testapp.txt");  //can fail for number of reasons
    	    }
    			
    	    // This error may occur if the temp folder does not exist.
    	    catch(IOException ioe)
    	    {
    		Console.WriteLine("An IO error ocurred. The c:\\temp folder does not exist");
    	    }
    
    	    // You do not have the appropriate permission to take this action.
    	    catch(SecurityException se)
    	    {
    		Console.WriteLine("You don't have the security permissions to take this action!");				
    	    }
    
    	    // Catch all exceptions.
    	    catch(Exception e)  
    	    {
    		Console.WriteLine(e.ToString());
    	    }
    	}
        }
    } 
    						
    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, refer to the Microsoft .NET Framework Software Development Kit (SDK).

Properties

Article ID: 308345 - Last Review: December 11, 2006 - Revision: 3.4
APPLIES TO
  • Microsoft Visual C# 2005
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords: 
kbhowtomaster KB308345

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