3

使用finally有什么区别

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...
}

并且不使用它?

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);
    }

    if (file != null)
    {
        file.Close();
    }

    // Do something with buffer...
}
4

4 回答 4

6

file.Close()无论是否抛出异常或抛出什么异常,前一个示例都将运行。

后者只有在没有抛出异常或抛出 a 时才会运行System.IO.IOException

于 2010-12-23T14:29:44.957 回答
3

不同之处在于,如果您不使用finally并且抛出除异常之外IOException的异常,您的应用程序将泄漏文件句柄,因为.Close永远不会到达该行。

就我个人而言,在处理流等一次性资源时,我总是使用using块:

try
{
    using (var reader = File.OpenText(@"c:\users\public\test.txt"))
    {
        char[] buffer = new char[10];
        reader.ReadBlock(buffer, index, buffer.Length);
         // Do something with buffer...
    }
}
catch (IOException ex)
{
    Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}

这样我就不必担心妥善处理它们。try/finally 的东西由编译器处理,我可以专注于逻辑。

于 2010-12-23T14:29:33.660 回答
1

您的 catch 块本身可能会引发异常(考虑path空引用时的情况)。或者块中抛出的异常try不是System.IO.IOException,所以不处理。除非使用文件句柄,否则在这两种情况下都不会关闭文件句柄finally

于 2010-12-23T14:33:44.883 回答
0

在你的情况下,什么都没有。如果您让异常从 catch 块中抛出,那么 finally 部分会运行,但其他变体不会。

于 2010-12-23T14:29:38.763 回答