【发布时间】:2010-09-12 19:56:20
【问题描述】:
我看到有人说不带参数使用 catch 是不好的形式,特别是如果那个 catch 没有做任何事情:
StreamReader reader=new StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
catch // No args, so it will catch any exception
{}
reader.Close();
但是,这被认为是好的形式:
StreamReader reader=new StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
finally // Will execute despite any exception
{
reader.Close();
}
据我所知,将清理代码放在 finally 块中和将清理代码放在 try..catch 块之后的唯一区别是,如果你的 try 块中有 return 语句(在这种情况下,清理代码in finally 会运行,但是 try..catch 之后的代码不会)。
要不然finally有什么特别的?
【问题讨论】:
-
在你试图抓住一只你无法应付的老虎之前,你应该记录下你最后的愿望。
-
Exceptions 文档中的主题可能会提供一些很好的见解。另请查看Finally Block 示例。
标签: c# .net exception-handling try-catch try-catch-finally