共用方式為


try-catch-finally (C# 參考)

更新:2007 年 11 月

catch 與 finally 常一起使用於獲得與使用 try 區塊中的資源、處理 catch 區塊中的例外狀況,以及釋放 finally 區塊中的資源時。

如需重新擲回例外狀況的詳細資訊和範例,請參閱 try-catch擲回例外狀況

範例

public class EHClass
{
    void ReadFile(int index)
    {
        // To run this code, substitute a valid path from your local machine
        string path = @"c:\users\public\test.txt";
        System.IO.StreamReader file = new System.IO.StreamReader(path);
        char[] buffer = new char[10];
        try
        {
            file.ReadBlock(buffer, index, buffer.Length);
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
        }

        finally
        {
            if (file != null)
            {
                file.Close();
            }
        }
        // Do something with buffer...
    }

}

C# 語言規格

如需詳細資料,請參閱 C# 語言規格中的下列章節:

  • 5.3.3.15 try-catch-finally 陳述式

  • 8.10 try 陳述式

  • 16 例外狀況

請參閱

工作

HOW TO:明確擲回例外狀況

概念

C# 程式設計手冊

參考

C# 關鍵字

The try, catch, and throw Statements

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

throw (C# 參考)

using 陳述式 (C# 參考)

其他資源

C# 參考