finally中的代码一定会执行吗?try里有return,finally还执行么

105 阅读1分钟

在Java官方文档中对finally的描述如下:

The finally block always executes when the try block exits. 大致意思是:finally代码块中的内容一定会得到执行。

JVM规范里面同样也有明确说明

If the try clause executes a return, the compiled code does the following:

  1. Saves the return value (if any) in a local variable.
  2. Executes a jsr to the code for the finally clause.
  3. Upon return from the finally clause, returns the value saved in the local variable. 意思是如果在try中存在return的情况下,会把try中return的值存到栈帧的局部变量表中,然后去执行finally语句块,最后再从局部变量表中取回return的值返回。另外,当try和finally里都有return时,会忽略try的return,而使用finally的return。

特殊情况 在正常情况下,finally中的代码一定会得到执行,但是如果我们将执行try-catch-finally 代码块的线程设置为守护线程,或者在fianlly之前调用System.exit结束当前虚拟机,那么finally则不会得到执行:

try{ System.exit(0); }catch (Exception e){

}finally {

}

Thread t1 = new Thread(){ @Override public void run(){ //try-catch-finally } }; t1.setDaemon(true);//设置为守护进程 t1.start();