try-finally (C# 參考)try-finally (C# Reference)

使用 finally 區塊,即可清除 try 區塊中所配置的任何資源,以及執行程式碼,即使 try 區塊中發生例外狀況也是一樣。By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block. 一般而言,會在控制權離開 try 陳述式時,執行 finally 區塊的陳述式。Typically, the statements of a finally block run when control leaves a try statement. 控制權轉移可能是正常執行、執行 breakcontinuegotoreturn 陳述式,或是傳播 try 陳述式的例外狀況所造成。The transfer of control can occur as a result of normal execution, of execution of a break, continue, goto, or return statement, or of propagation of an exception out of the try statement.

在處理的例外狀況內,一定會執行關聯的 finally 區塊。Within a handled exception, the associated finally block is guaranteed to be run. 不過,如果無法處理例外狀況,則執行 finally 區塊取決於如何觸發例外狀況回溯作業。However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. 接著,取決於您電腦的設定方式。That, in turn, is dependent on how your computer is set up.

通常,未處理的例外狀況結束應用程式時,是否執行 finally 區塊並不重要。Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. 不過,如果您的 finally 區塊中有即使在這種情況下都必須執行的陳述式,則其中一個解決方案是將 catch 區塊新增至 try-finally 陳述式。However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement. 或者,您可以攔截可能會在呼叫堆疊較高之 try-finally 陳述式的 try 區塊中擲回的例外狀況。Alternatively, you can catch the exception that might be thrown in the try block of a try-finally statement higher up the call stack. 亦即,您可以攔截下列方法中的例外狀況:呼叫包含 try-finally 陳述式的方法、呼叫該方法的方法,或呼叫堆疊的任何方法。That is, you can catch the exception in the method that calls the method that contains the try-finally statement, or in the method that calls that method, or in any method in the call stack. 如果未攔截到例外狀況,則執行 finally 區塊取決於作業系統是否選擇觸發例外狀況回溯作業。If the exception is not caught, execution of the finally block depends on whether the operating system chooses to trigger an exception unwind operation.

範例Example

在下列範例中,無效的轉換陳述式會導致 System.InvalidCastException 例外狀況。In the following example, an invalid conversion statement causes a System.InvalidCastException exception. 例外狀況未進行處理。The exception is unhandled.

public class ThrowTestA
{
    static void Main()
    {
        int i = 123;
        string s = "Some string";
        object obj = s;

        try
        {
            // Invalid conversion; obj contains a string, not a numeric type.
            i = (int)obj;

            // The following statement is not run.
            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("\nExecution of the finally block after an unhandled\n" +
                "error depends on how the exception unwind operation is triggered.");
            Console.WriteLine("i = {0}", i);
        }
    }
    // Output:
    // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
    //
    // Execution of the finally block after an unhandled
    // error depends on how the exception unwind operation is triggered.
    // i = 123
}

在下列範例中,會攔截到來自呼叫堆疊最遠的方法中之 TryCast 方法的例外狀況。In the following example, an exception from the TryCast method is caught in a method farther up the call stack.

public class ThrowTestB
{
    static void Main()
    {
        try
        {
            // TryCast produces an unhandled exception.
            TryCast();
        }
        catch (Exception ex)
        {
            // Catch the exception that is unhandled in TryCast.
            Console.WriteLine
                ("Catching the {0} exception triggers the finally block.",
                ex.GetType());

            // Restore the original unhandled exception. You might not
            // know what exception to expect, or how to handle it, so pass 
            // it on.
            throw;
        }
    }

    public static void TryCast()
    {
        int i = 123;
        string s = "Some string";
        object obj = s;

        try
        {
            // Invalid conversion; obj contains a string, not a numeric type.
            i = (int)obj;

            // The following statement is not run.
            Console.WriteLine("WriteLine at the end of the try block.");
        }
        finally
        {
            // Report that the finally block is run, and show that the value of
            // i has not been changed.
            Console.WriteLine("\nIn the finally block in TryCast, i = {0}.\n", i);
        }
    }
    // Output:
    // In the finally block in TryCast, i = 123.

    // Catching the System.InvalidCastException exception triggers the finally block.

    // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
}

如需 finally 的詳細資訊,請參閱 try-catch-finallyFor more information about finally, see try-catch-finally.

C# 也會包含 using 陳述式,以透過方便使用的語法提供 IDisposable 物件的類似功能。C# also contains the using statement, which provides similar functionality for IDisposable objects in a convenient syntax.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格try 陳述式一節。For more information, see The try statement section of the C# language specification.

另請參閱See also