Aracılığıyla paylaş


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.

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.

    public class ThrowTest
    {
        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;

                Console.WriteLine("WriteLine at the end of the try block.");
            }
            finally
            {
                // To run the program in Visual Studio, type CTRL+F5. Then 
                // click Cancel in the error dialog.
                Console.WriteLine("\nThe finally block is executed, even though"
                    + " an error was caught in the try block.");
                Console.WriteLine("i = {0}", i);
            }
        }
        // Output:
        // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
        // at ValueEquality.ThrowTest.Main() in c:\users\sahnnyj\documents\visual studio
        // 2010\Projects\ConsoleApplication9\Program.cs:line 21
        //
        // The finally block is executed, even though an error was caught in the try block.
        // i = 123
    }

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.

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Tasks

How to: Explicitly Throw Exceptions

Reference

C# Keywords

try, catch, and throw Statements (C++)

Exception Handling Statements (C# Reference)

throw (C# Reference)

try-catch (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference

Change History

Date

History

Reason

May 2010

Added write statements and instructions in the example to clarify the results.

Customer feedback.