Java:关于finally块的假设问题
如果在finally 块中抛出错误会发生什么?它是否在相应的 catch 子句之一中得到处理?
What happens if you throw an error in a finally block? Does it get handled in one of the corresponding catch clauses?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
执行顺序一般直接用语句的顺序来表示:1.try,2.按照指定的顺序catch异常(只执行一个catch),3.finally。
因此,当执行finally块时(请注意,情况总是如此,即使在try或catch块中抛出return语句或异常的情况下),try语句的执行处于最后阶段,因此无法捕获进一步的投掷物。正如已经指出的,异常必须在堆栈中更下方(或上方,取决于观点;))的位置进行处理。
The order of execution is normally directly indicated by the order of statements: 1. try, 2. catch exceptions in the specified order (only one catch is executed), 3. finally.
So when the finally block is executed (note that this is always the case, even in the case of a return statement or exception being thrown in the try or catch blocks) the execution of try statement is in its last phase and thus it cannot catch further throwables. As already pointed out, the exception has to be handled in a location further down the stack (or up, depends on the view point ;) ).
仅当您在finally 块中放置另一个try-catch 块时。否则,它就像其他错误一样。
Only if you put another try-catch block in the finally block. Otherwise it's an error like any other.
您需要在finally 或catch 块中包含try-catch 块。
例如:
You need to include try-catch blocks inside the finally or catch blocks.
e.g.:
它不会处理异常,直到它自己被finally块捕获为止。
上面的代码会抛出异常,但如果你按如下方式执行,它将起作用:
It will not handle exception until it is caught in finally block it self.
Above code will throw exception but if you do as follows it will work:
没有。它会被一个 catch 捕获,然后整个 try/catch/finally 嵌套在另一个 try/catch 中。否则,异常将被抛出函数之外,并由函数的调用者处理。
Nope. It would be caught by a catch where then entire try/catch/finally was nested within another try/catch. The exception would otherwise be thrown out of the function, and would be handled by the caller of the function.
不,没有。您必须在 finally 块中处理它,或者在方法描述中定义正确的 throw 声明。
No it doesn't. You will have to handle with it IN the finally block or define a proper throw declaration in the method description.
不可以,catch 块只能捕获相应
try
块中引发的异常,而不能捕获finally
块中引发的异常。 (当然,如果该finally
块位于另一个try
块内,则该try
块的 catch 子句为仍在使用。)JLS 中的相关部分是 14.20.2。那里列出的每个流程都有这样的内容:
换句话说,不会尝试与
finally
块关联的任何catch
子句来处理异常。No, a catch block can only catch exceptions thrown within the corresponding
try
block - not afinally
block. (Of course, if thatfinally
block is within anothertry
block, the catch clauses for thattry
block are still used.)The relevant section in the JLS is 14.20.2. Each of the flows listed there has something like this:
In other words, there's no attempt for any
catch
clauses associated with thefinally
block to handle the exception.