这个“try..catch..finally”是多余的吗?
public Foo doDangerousStuff() throws Exception {
try {
dangerousMethod();
return new Foo();
} catch (Exception e) {
throw e;
} finally {
mustBeCalledAfterDangerousMethod();
}
}
这与我们省略 catch 子句的行为有什么不同吗?
public Foo doDangerousStuff() throws Exception {
try {
dangerousMethod();
return new Foo();
} finally {
mustBeCalledAfterDangerousMethod();
}
}
[编辑] 为了消除混乱,是的,catch 块除了重新抛出异常之外什么也不做。我想知道这是否会在调用 finally
块时导致某种不同的顺序(假设抛出的异常被调用者捕获),但从我迄今为止的答案推断,它确实不是。
public Foo doDangerousStuff() throws Exception {
try {
dangerousMethod();
return new Foo();
} catch (Exception e) {
throw e;
} finally {
mustBeCalledAfterDangerousMethod();
}
}
Does this behave any differently than if we were to omit the catch clause?
public Foo doDangerousStuff() throws Exception {
try {
dangerousMethod();
return new Foo();
} finally {
mustBeCalledAfterDangerousMethod();
}
}
[edit] To clear the confusion, yes, the catch
block does nothing except re-throw the exception. I was wondering if this caused some sort of different ordering in when the finally
block is invoked (assume that the thrown exception is caught by the caller), but from what I infer from the answers thusfar, it does not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
他们是一样的。我会使用第二个版本。
They are the same. I would use the second version.
是的。由于您的方法已经抛出“异常”,因此您不需要捕获它并重新抛出它。除非你想做@Dave 提到的事情。
Yes. Since your method already throws "Exception", you dont need to catch it and re-throw it. Unless you want do what @Dave mentioned.
尽管两个源代码代表相同的执行顺序,但它们将产生不同的字节码。例如,第一个例程将有一个异常表,而第二个例程则不会。在没有检测的情况下,它们的字节码在执行期间将具有相同的效果。如果编译后对字节码进行检测,或者捕获的异常属于其类文件在执行期间不可用的类型,则这些方法的行为可能会有所不同。
Though the two source codes represent the same execution sequence, they will result in different bytecode. The first routine will have an exception table, for example, whereas the second will not. Their bytecode will have the same effect during execution, in the absence of instrumentation. It is possible that these methods behave differently if the bytecode is instrumented after compilation, or if the caught exception is of a type whose classfile is not available during execution.
当您抛出在 catch 子句中捕获的异常时,除了再次抛出它之外什么也不做,是的,两个代码都会做同样的事情。
As you are throwing the exception you have caught in the catch clause and doing nothing else but throwing it again, yes both code will do the same thing.
你说得对,是一样的。甚至堆栈跟踪也会在那里:)
但是如果您将异常包装到某个更高级别的异常中,则可能会使用类似的代码。如果代码看起来完全像所说的那样,那真的毫无意义。
You are right, it is the same. Even the stacktrace will be there :)
But similar code might be use if you wrap the exception into some higher level one. If the code looks exactly like stated it is really pointless.