是一个finally块没有一个catch块一个java反模式? [英] Is a finally block without a catch block a java anti-pattern?

查看:100
本文介绍了是一个finally块没有一个catch块一个java反模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在一些故障排除code,看上去像这样的pretty痛苦的故障排除经验:

I just had a pretty painful troubleshooting experience in troubleshooting some code that looked like this:

try {
   doSomeStuff()
   doMore()
} finally {
   doSomeOtherStuff()
}

问题是难以解决,因为doSomeStuff()抛出一个异常,进而引起doSomeOtherStuff()也抛出一个异常。第二个例外(由finally块抛出)被抛出了我的code,但它并没有对第一异常的手柄,这是问题的真正根源(从doSomeStuff()抛出)。

The problem was difficult to troubleshoot because doSomeStuff() threw an exception, which in turn caused doSomeOtherStuff() to also throw an exception. The second exception (thrown by the finally block) was thrown up to my code, but it did not have a handle on the first exception (thrown from doSomeStuff()), which was the real root-cause of the problem.

如果在code曾表示,这不是,那问题就已经很明显:

If the code had said this instead, the problem would have been readily apparent:

try {
    doSomeStuff()
    doMore()
} catch (Exception e) {
    log.error(e);
} finally {
   doSomeOtherStuff()
}

所以,我的问题是这样的:

So, my question is this:

时finally块没有任何抓用块一个著名的Java反模式? (这当然似乎是明显的著名反模式的一个不容易,显然子不要狼吞虎咽例外!)

Is a finally block used without any catch block a well-known java anti-pattern? (It certainly seems to be a not-readily-apparent subclass of the obviously well-known anti-pattern "Don't gobble exceptions!")

推荐答案

在一般情况下,不,这不是一个反模式。 finally块的一点是要确保得到的东西清理一个是否引发异常与否。异常处理的整点是,如果你不能处理它,你让IT泡沫到谁可以通过比较干净外的带外信令异常处理提供。如果你需要确保得到的东西清理如果有异常被抛出,但不能正确地处理这个异常在目前的范围内,那么这正是做正确的事情。你只是可能要多一点小心确保您的finally块不会抛出。

In general, no, this is not an anti-pattern. The point of finally blocks is to make sure stuff gets cleaned up whether an exception is thrown or not. The whole point of exception handling is that, if you can't deal with it, you let it bubble up to someone who can, through the relatively clean out-of-band signaling exception handling provides. If you need to make sure stuff gets cleaned up if an exception is thrown, but can't properly handle the exception in the current scope, then this is exactly the correct thing to do. You just might want to be a little more careful about making sure your finally block doesn't throw.

这篇关于是一个finally块没有一个catch块一个java反模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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