有什么用最后尝试抓点终于块?
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...
}
catch块可能重新抛出错误,提出一个新的等,这将绕过最后关闭。看到这里 - http://stackoverflow.com/questions/50618/what-is-the-point-of-the-finally-block – StuartLC 2010-12-23 14:29:15
我知道别人会输出一个答案比我可以更快,但你有没有考虑造成IOException并为自己看到不同之处? – ChaosPandion 2010-12-23 14:30:04