2010-12-23 46 views
3

有什么用最后尝试抓点终于块?

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

catch块可能重新抛出错误,提出一个新的等,这将绕过最后关闭。看到这里 - http://stackoverflow.com/questions/50618/what-is-the-point-of-the-finally-block – StuartLC 2010-12-23 14:29:15

+0

我知道别人会输出一个答案比我可以更快,但你有没有考虑造成IOException并为自己看到不同之处? – ChaosPandion 2010-12-23 14:30:04

回答

7

前面的示例将运行file.Close(),无论是否抛出异常或引发了什么异常。

后者只会运行,如果没有抛出异常或者抛出System.IO.IOException

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的东西由编译器处理,我可以专注于逻辑。

+0

是啊我刚刚复制并粘贴了一个例子,如果我没有指定只是IOExceptions? – bevacqua 2010-12-23 14:31:41

0

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

1

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