Share via


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.

Remarks

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.

Example

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.

// try-finally
using System;
public class MainClass
{
    static void Main()
    {
        int i = 123;
        string s = "Some string";
        object o = s;

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

Comments

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# Language Specification

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

  • 5.3.3.14 Try-finally statements

  • 8.11 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)
try-catch (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference