我见过有人说,使用不带参数的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块中有返回语句(在这种情况下,finally中的清理代码将运行,但try. catch块之后的代码将不会运行)。

否则,最后有什么特别的?


当前回答

try/catch块捕获所有异常的问题是,如果发生未知异常,您的程序现在处于不确定状态。这完全违背了快速失败规则——如果发生异常,您不希望程序继续运行。上面的try/catch甚至会捕获outofmemoryexception,但这绝对是程序不会在其中运行的状态。

Try/finally块允许您在快速失败的情况下执行清理代码。对于大多数情况,您只想在全局级别捕获所有异常,以便您可以记录它们,然后退出。

其他回答

可能有很多原因,其中之一就是异常执行非常慢。如果这种情况经常发生,很容易缩短执行时间。

添加catch子句只是为了重新抛出异常,这是一种糟糕的实践。

finally块仍然会抛出任何引发的异常。最后要做的就是确保在抛出异常之前运行清理代码。

The try..catch with an empty catch will completely consume any exception and hide the fact that it happened. The reader will be closed, but there's no telling if the correct thing happened. What if your intent was to write i to the file? In this case, you won't make it to that part of the code and myfile.txt will be empty. Do all of the downstream methods handle this properly? When you see the empty file, will you be able to correctly guess that it's empty because an exception was thrown? Better to throw the exception and let it be known that you're doing something wrong.

另一个原因是这样做的try. catch是完全错误的。你这样做的意思是,“无论发生什么,我都能处理好。”StackOverflowException呢,你能在那之后清理吗?OutOfMemoryException呢?一般来说,您应该只处理您期望并知道如何处理的异常。

最后无论如何都会执行。如果你的try块成功,它就会执行,如果你的try块失败,它就会执行catch块,然后是finally块。

此外,最好尝试使用以下结构:

using (StreamReader reader=new  StreamReader("myfile.txt"))
{
}

由于using语句被自动包装在try / finally语句中,流将自动关闭。(如果想要真正捕获异常,则需要在using语句周围加上try / catch)。

“Finally”是一个声明,“你必须总是做一些事情来确保程序状态正常”。因此,如果存在异常可能会抛出程序状态,那么拥有一个异常总是很好的形式。编译器还会竭尽全力确保Finally代码运行。

“Catch”是“我可以从这个异常中恢复”的声明。您应该只从真正可以纠正的异常中恢复—不带参数的catch表示“嘿,我可以从任何异常中恢复!”,这几乎总是不正确的。

如果有可能从每个异常中恢复,那么它就真的是语义上的吹毛求疵,关于你所声明的意图是什么。然而,事实并非如此,而且几乎可以肯定的是,在你上面的框架能够更好地处理某些异常。因此,使用finally,让您的清理代码免费运行,但仍然让更有知识的处理程序来处理问题。