Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual C#
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
C# Programming Guide
Exceptions and Exception Handling (C# Programming Guide)

Updated: July 2008

The C# language's exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running. Exception handling uses the try, catch, and finally keywords to try actions that may not succeed, to handle failures when you decide that it is reasonable to do so, and to clean up resources afterward. Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any third-party libraries, or by application code. Exceptions are created by using the throw keyword.

In many cases, an exception may be thrown not by a method that your code has called directly, but by another method further down in the call stack. When this happens, the CLR will unwind the stack, looking for a method with a catch block for the specific exception type, and it will execute the first such catch block that if finds. If it finds no appropriate catch block anywhere in the call stack, it will terminate the process and display a message to the user.

In this example, a method tests for division by zero and catches the error. Without the exception handling, this program would terminate with a DivideByZeroException was unhandled error.

C#
class ExceptionTest
{
    static double SafeDivision(double x, double y)
    {
        if (y == 0)
            throw new System.DivideByZeroException();
        return x / y;
    }
    static void Main()
    {
        // Input for test purposes. Change values
        // to see exception handling behavior.
        double a = 98, b = 0;
        double result = 0;

        try
        {
            result = SafeDivision(a, b);
            Console.WriteLine("{0} divided by {1} = {2}", a, b, result);
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine("Attempted divide by zero.");
        }
    }
}

Exceptions have the following properties:

  • Exceptions are types that all ultimately derive from System.Exception.

  • Use a try block around the statements that might throw exceptions.

  • Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. In C#, the catch keyword is used to define an exception handler.

  • If no exception handler for a given exception is present, the program stops executing with an error message.

  • Do not catch an exception unless you can handle it and leave the application in a known state. If you catch System.Exception, rethrow it using the throw keyword at the end of the catch block.

  • If a catch block defines an exception variable, you can use it to obtain more information about the type of exception that occurred.

  • Exceptions can be explicitly generated by a program by using the throw keyword.

  • Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error.

  • Code in a finally block is executed even if an exception is thrown. Use a finally block to release resources, for example to close any streams or files that were opened in the try block.

  • Managed exceptions in the .NET Framework are implemented on top of the Win32 structured exception handling mechanism. For more information, see Structured Exception Handling (C++) and A Crash Course on the Depths of Win32 Structured Exception Handling.

For more information, see the following sections in the C# Language Specification:

  • 8.9.5 The throw statement

  • 8.10 The try statement

  • 16 Exceptions

Date

History

Reason

July 2008

Modified code example and added text about unwinding the stack.

Content bug fix.

July 2008

Added example to explanation of the finally block.

Information enhancement.

July 2008

Added information about the Win32 structured exception handling mechanism.

Information enhancement.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
CodePlex.Diagnostics      Doug Holland MVP   |   Edit   |   Show History
In addition to the Microsoft Enterprise Library which provides the ability to publish exceptions, you might consider looking at the CodePlex.Diagnostics library available at http://www.codeplex.com/diagnostics/.

CodePlex.Diagnostics is based upon the ASP.NET provider pattern introduced in the .NET Framework 2.0 and contains default providers for exception publication and logging. Using the default providers the exceptions and log entries are written to the SQL Server 2005 / 2008 database although additional providers can easily be integrated into the framework to target other databases with ease.

One major benefit to the CodePlex.Diagnostics framework is that it also stores additional information about an exception that could be useful in determining the cause of the exception. Examples of this additional information include the Process, AppDomain, and Thread within which an exception occurred.
Processing
© 2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker