Using finally block vs writing code after the try/catch block

倖福魔咒の 提交于 2020-01-12 18:23:12

问题


As I understand, the following 2 examples should do the same thing. Why is the 1st considered better?

1:

try {
  riskyMethod();
}
catch(Exception e) {
  //handle exception
}
finally {
  cleanUp();
}

2:

try {
  riskyMethod();
}
catch(Exception e) {
  //handle exception
}
cleanUp();

EDIT: The example is in Java, but I'm wondering about the concept of a finally block in general, as used in any language


回答1:


Well, for one thing if the "handle exception" part throws an exception itself, cleanup won't occur.

More importantly though, you should almost never be catching all exceptions. You should catch very specific exceptions you can handle, and let other exceptions bubble up. At that point, you must use a finally block if you want the cleanup to still occur.

It's not clear what language you're using, but if it's Java then there's already a difference, as non-Exception exceptions (other subclasses of Throwable) will end up cleaning up in your first version but not in your second - but you shouldn't even catch Exception generally.

Personally I find I write more try/finally blocks than try/catch or try/catch/finally blocks. I find it pretty rare that I can really deal with an exception... although sometimes I catch one exception just to convert it to one more appropriate for the abstraction level I'm working on, and then rethrow.

EDIT: As noted in dj aqeel's answer, finally statements are also executed if the block completes without an exception, e.g. through a return statement. The very fact that I'd forgotten that is a good reason to favour finally: it promotes consistency. It's one consistent place to perform clean-up, regardless of how the block is exited.

Also note that in C#, you'd idiomatically use a using statement for disposable resources. And Java 7 has the try-with-resources statement.




回答2:


Because the code in finally block always executes, even if you have return statements, exceptions, or other control leaving statements in try or catch blocks... finally will always execute in any case other than you power off the machine just before finally block. :)




回答3:


Because "finally" is a clear indication that you're doing the cleanup here.



来源:https://stackoverflow.com/questions/7426540/using-finally-block-vs-writing-code-after-the-try-catch-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!