lz这个问题很好!“finally一定会被执行”是一个含糊不严谨的说法。还是Java官方的the Java tutorial说得清楚:
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
也就是说,如果JVM退出了,或者try/finally所在的线程被中断了,那么finally块就可能不会被执行。另外,官方tutorial用的是“may not”,并没有说在JVM退出或线程中断时finally就一定不会执行,这可能跟JVM的实现规范有关,具体要参考JVM specification和Java language specification两份文档 |