我见过有人说,使用不带参数的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块之后的代码将不会运行)。

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


当前回答

从可读性的角度来看,它更明确地告诉未来的代码读者“这里的东西很重要,无论发生什么都需要完成。”这很好。

此外,空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呢?一般来说,您应该只处理您期望并知道如何处理的异常。

最大的区别是尝试…Catch将吞下异常,隐藏发生错误的事实。Try .finally将运行您的清理代码,然后异常将继续运行,由知道如何处理它的程序来处理。

从可读性的角度来看,它更明确地告诉未来的代码读者“这里的东西很重要,无论发生什么都需要完成。”这很好。

此外,空catch语句对它们来说往往有某种“味道”。它们可能表明开发人员没有仔细考虑可能发生的各种异常以及如何处理它们。

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

因为当这一行引发异常时,你不会知道。

对于第一个代码块,异常将被简单地吸收,即使程序的状态可能是错误的,程序也将继续执行。

对于第二个块,将抛出异常并出现冒泡,但reader.Close()仍然保证运行。

如果不期望出现异常,那么就不要使用try. catch块,这样当程序进入糟糕的状态而你不知道原因时,就很难进行调试。