finally语句块一定会执行吗?
?
按理說(shuō)finally是一定執(zhí)行的,但也不排除特例,比如說(shuō)以下代碼:
public class SystemExitAndFinally {
??? public static void main(String[] args)
??? {
??????? try{
??????????? System.out.println("in main");
??????????? throw new Exception("Exception is thrown in main");
???????????
??????? }
??????? catch(Exception e) ??????? {
??????????? System.out.println(e.getMessage());
??????????? System.exit(0); ??????? }
??????? finally ??????? {
??????????? System.out.println("in finally");
??????? }
??? }
}
?
它的運(yùn)行結(jié)果只有
in main
Exception is thrown in main
我們發(fā)現(xiàn)他的finally沒(méi)有執(zhí)行
這是因?yàn)?System.exit(status);這個(gè)方法是用來(lái)結(jié)束當(dāng)前正在運(yùn)行中的java虛擬機(jī)。如何status是非零參數(shù),那么表示是非正常退出。
轉(zhuǎn)載于:https://www.cnblogs.com/hehejeson/articles/4963925.html
總結(jié)
以上是生活随笔為你收集整理的finally语句块一定会执行吗?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: try、catch、finally的执行
- 下一篇: 2016年第一堂课课后作业1