try-finally (C# 參考)

更新:2010 年 5 月

finally 區塊對於清除 try 區塊中配置的任何資源,以及執行即使有例外狀況也必須執行的任何程式碼十分有用。 不論 try 區塊如何結束,程式控制權最後都轉移到 finally 區塊。

就像 catch 是用來處理陳述式區塊中所發生的例外狀況一樣,finally 也是用來保證某一陳述式區塊的程式碼一定會執行,無論前一個 try 區塊如何結束都不會影響。

範例

在這個範例中,有一個造成例外狀況的無效轉換陳述式。 當您執行程式時,將得到執行階段錯誤訊息,但是 finally 子句仍會執行並且顯示輸出。

    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
    }

上述範例會導致擲回 System.InvalidCastException。

雖然已經攔截到例外狀況,但是仍然會執行包含於 finally 區塊內的輸出陳述式,也就是:

i = 123

如需 finally 的詳細資訊,請參閱 try-catch-finally

C# 也提供了 using 陳述式,以提供功能與 try-finally 陳述式相同的方便語法。

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格。 語言規格是 C# 語法和用法的決定性來源。

請參閱

工作

HOW TO:明確擲回例外狀況

參考

C# 關鍵字

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

例外處理陳述式 (C# 參考)

throw (C# 參考)

try-catch (C# 參考)

概念

C# 程式設計手冊

其他資源

C# 參考

變更記錄

日期

記錄

原因

2010 年 5 月

在範例中新增寫入陳述式和指令,以說明結果。

客戶回函。