Collapse the table of content
Expand the table of content
This documentation is archived and is not being maintained.

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.

// try_catch_finally.cs
using System;
public class EHClass
    static void Main()
            Console.WriteLine("Executing the try statement.");
            throw new NullReferenceException();
        catch (NullReferenceException e)
            Console.WriteLine("{0} Caught exception #1.", e);
            Console.WriteLine("Caught exception #2.");
            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.

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

  • Try-catch-finally statements

  • 8.10 The try statement

  • 16 Exceptions

© 2016 Microsoft