try-finally

今天写一下有关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(),就不会执行了。是不是很神奇!




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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容