try里有return,finally 里还会执行吗?

经常用到try catch finally 结构,遇到return 具体执行顺序是啥样的?

finnaly 经常被用在需要释放资源的情况下去使用,最终一定要执行一下,但是有两种情况,finally 代码块也不会被执行

1 程序在进入try之前就异常了,就直接结束了,不会进入finally。

2 try中遇到强制退出的情况(比如 exit),也不会进入finally 执行。

正题解答:

 try中有return, 会先将值暂存,无论finally语句中对该值做什么处理,最终返回的都是try语句中的暂存值。

当try和finally里都有return时,会忽略try的return,而使用finally的return。

根据: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.

posted on 2020-09-24 13:32  靠自己的骨头长肉  阅读(868)  评论(0编辑  收藏  举报