美文网首页
try-finally

try-finally

作者: 乐百事52淑熙 | 来源:发表于2018-05-10 21:57 被阅读0次

今天写一下有关Try-Finally的相关问题吧。

如果代码块中有try,catch,finally,哪个会执行?

首先:我们知道,如果在try{     }中有异常,catch{    }中的代码会执行。finally{    }中的代码不管如何都会执行。

如果try{    }中有return,finally{    }是否会执行?

看一下下面这个代码:

public class Try_Finallly {

public static void main(String[] args) {

System.out.println(tryFinalTest());

    }

private static int tryFinalTest() {

try{

return 1;

        }finally {

return 2;

        }

}

}

上面的代码输出结果为:2,finally{    }执行了。在try{    }中的return之前执行,因为finally{    }中存在return,所以不再执行之前的。

再看一个代码:

public class Try_Finallly {

public static void main(String[] args) {

System.out.println(tryFinalTest());

    }

private static int tryFinalTest() {

int x =1;

        try{

return x++;

        }finally {

             x++;

        }

}

}

你认为会输出多少?

正确答案:2

finally中的x++也是执行了的。

产生疑问了?首先要说的是:finally{    }中的代码不管何时都会执行,因为这样可以在产生异常时,释放清理资源。我们经常将锁在finally中释放就是这个道理。

但是为什么结果还是2呢?

JVM做出了解释:If the try clause executes a return, the compiled code does the following:

Saves the return value (if any) in a local variable.

Executes a jsr to the code for the finally clause.

Upon return from the finally clause, returns the value saved in the local variable.

如果try中存在返回值,将返回值存在局部变量

执行jsr指令到finally中

执行完finally之后,返回本地存的局部变量。

是不是懂了?

最后敲个黑板!!!

是不是真的任何时候都会执行finally?

不是的,如果你在try{    }中执行system.exit(),就不会执行了。是不是很神奇!

个人公号:【排骨肉段】,可以关注一下。

相关文章

网友评论

      本文标题:try-finally

      本文链接:https://www.haomeiwen.com/subject/vzitdftx.html