Using finally block vs writing code after the try/

2020-07-06 08:17发布

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

3条回答
混吃等死
2楼-- · 2020-07-06 08:48

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楼-- · 2020-07-06 09:07

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.

查看更多
太酷不给撩
4楼-- · 2020-07-06 09:11

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

查看更多
登录 后发表回答