整理总结
EmbedFinally.java运行结果:
finally语句块一定会执行吗?SystemExitAndFinally.java
public class SystemExitAndFinally { public static void main(String[] args) { try{ System.out.println("in main"); throw new Exception("Exception is thrown in main"); //System.exit(0); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(0); } finally { System.out.println("in finally"); } } }
运行结果:
显然并不是一定执行。
存在很多特殊情况导致 finally 语句块不执行。如:
直接返回未执行到 try-finally 语句块
抛出异常未执行到 try-finally 语句块
系统退出未执行到 finally 语句块