【发布时间】:2025-12-17 21:10:01
【问题描述】:
和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...
}
【问题讨论】:
-
catch 块可能会重新抛出错误,引发新错误等,这将绕过 finally 的关闭。见这里 - *.com/questions/50618/…
-
我知道其他人会比我更快地输入答案,但您是否考虑过导致 IOException 并亲自查看差异?
标签: c# try-catch try-catch-finally