try-catch-finally(C# 参考)

catchfinally 一起使用的常见方式是:在 try 块中获取并使用资源,在 catch 块中处理异常情况,并在 finally 块中释放资源。

有关重新引发异常的更多信息和示例,请参见 try-catch“引发异常”。有关 finally 的更多信息,请参见 尝试最终块。

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# 语言规范。该语言规范是 C# 语法和用法的权威资料。

请参阅

C# 参考

C# 编程指南

C# 关键字

try、throw 和 catch 语句 (C++)

异常处理语句(C# 参考)

throw(C# 参考)

如何:显式引发异常

using 语句(C# 参考)