在try / catch块之后使用finally块和编写代码 [英] Using finally block vs writing code after the try/catch block

查看:163
本文介绍了在try / catch块之后使用finally块和编写代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据了解,以下2个例子应该做同样的事情。为什么第一个考虑更好?



1:

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

2:

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

编辑:这个例子在Java中,但我想知道一个finally块的概念一般,在任何语言中使用

解决方案

嗯,有一件事情,如果处理异常部分本身抛出一个异常,不会发生。



更重要的是,您几乎不会抓住所有异常。您应该捕获可以处理的非常具体的异常,并允许其他异常起泡。在这一点上,如果您希望清理仍然发生,您必须使用终止块。



目前还不清楚您使用的是什么语言,但如果是Java,那么已经有了一个区别,因为非异常异常(Throwable的其他子类)将最终在您的第一个版本中清理,但是你通常不应该抓住异常



个人我发现我写的try / finally块比try / catch或try / catch / finally块。我发现很少见,我可以真正地处理一个异常...虽然有时我会捕获一个异常,只是为了将其转换为一个更适合我正在开发的抽象级别,然后重新抛出



编辑:如dj aqeel的回答所述,如果块完成也执行 finally 语句没有例外,例如通过返回语句。事实上,我忘了,这是一个很好的理由,赞成终于:它促进一致性。执行清理是一个一致的地方,不管块是否被退出。



另请注意,在C#中,您会习惯使用使用声明一次性资源。而Java 7则具有试用资源陈述。


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

解决方案

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.

这篇关于在try / catch块之后使用finally块和编写代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆