Collapse the table of content
Expand the table of content
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

try-finally (C# Reference)

The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.

Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.

In this example, there is one invalid conversion statement that causes an exception. When you run the program, you get a run-time error message, but the finally clause will still be executed and display the output.

public class ThrowTest
    static void Main()
        int i = 123;
        string s = "Some string";
        object o = s;

            // Invalid conversion; o contains a string not an int
            i = (int)o;
            Console.Write("i = {0}", i);

The example above causes System.InvalidCastException to be thrown.

Although an exception was caught, the output statement included in the finally block will still be executed, that is:

i = 123

For more information on finally, see try-catch-finally.

C# also provides the using statement which provides a convenient syntax for the exact same functionality as a try-finally statement.

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

  • Try-finally statements

  • 8.11 The try statement

  • 16 Exceptions

© 2016 Microsoft