最后和没有最后之间有什么区别? [英] What is the difference between finally and no finally?
问题描述
两者之间有什么区别
try {
// action A
}
catch(Exception e) {
// action B
}
finally {
// action C
}
和
try {
// action A
}
catch(Exception e) {
// action B
}
// action C
我读到您可以从catch
块内部返回,但仍然可以执行finally
块.还有其他区别吗?
I have read that you can return from inside a catch
block and still have the finally
block execute. Are there any other differences?
推荐答案
无论try-catch-block中发生什么,都保证发生在finally
块中的事情发生.如果发生了未被Exception
封装的异常(例如,扩展了Throwable
,例如各种Error
),则它 still 运行finally
块.
Things that happen within the finally
block are guaranteed to occur no matter what happens in the try-catch-block. If an exception happens that is not encapsulated by Exception
(e.g., extends Throwable
, such as various Error
s), then it still runs the finally
block.
要注意的一件事:如果在finally
块中抛出了RuntimeException
,或者另一个Exception
从其中逸出,则
One thing to be aware of: if, within the finally
block, a RuntimeException
is thrown, or another Exception
escapes from within it, then the rest of the finally
block will not execute. Also, as Lord Torgamus pointed out, it is contingent on the JVM running. In addition, and probably obviously, it is also contingent on the thread not being stopped.
这篇关于最后和没有最后之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!