try-catch-finally (C# Reference) 

A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.

For more information and examples on re-throwing exceptions, see try-catch and Throwing Exceptions.

Example

// try_catch_finally.cs
using System;
public class EHClass
{
    static void Main()
    {
        try
        {
            Console.WriteLine("Executing the try statement.");
            throw new NullReferenceException();
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine("{0} Caught exception #1.", e);
        }
        catch
        {
            Console.WriteLine("Caught exception #2.");
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }
    }
}

Sample Output

Executing the try statement.
System.NullReferenceException: Object reference not set to an instance of an object.
   at EHClass.Main() Caught exception #1.
Executing finally block.

C# Language Specification

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

  • 5.3.3.15 Try-catch-finally statements

  • 8.10 The try statement

  • 16 Exceptions

See Also

Tasks

How to: Explicitly Throw Exceptions

Reference

C# Keywords
The try, catch, and throw Statements
Exception Handling Statements (C# Reference)
throw (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference