我见过有人说,使用不带参数的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'子句中抛出异常,则第一个示例将完全忽略它。第二个示例将向调用堆栈的下一个步骤抛出异常,因此所述示例的区别在于,一个示例完全掩盖了任何异常(第一个示例),而另一个示例(第二个示例)保留了异常信息,以便后续处理,同时仍然执行'finally'子句中的内容。
例如,如果您将代码放在第一个示例的'catch'子句中,该子句抛出异常(无论是最初引发的异常还是新抛出的异常),则阅读器清理代码永远不会执行。最后执行,不管'catch'子句中发生了什么。
因此,'catch'和'finally'之间的主要区别是,'finally'块的内容(少数例外)可以被认为是保证执行的,即使面对意外的异常,而'catch'子句之后的任何代码(但在'finally'子句之外)都不会带有这样的保证。
顺便说一句,Stream和StreamReader都实现了IDisposable,并且可以包装在一个“using”块中。'Using'块在语义上等同于try/finally(没有'catch'),所以你的例子可以更简洁地表达为:
using (StreamReader reader = new StreamReader("myfile.txt"))
{
int i = 5 / 0;
}
...它会在StreamReader实例超出作用域时关闭并销毁它。
希望这能有所帮助。
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呢?一般来说,您应该只处理您期望并知道如何处理的异常。