finally块中的代码必定会执行吗?


    public static void main(String[] args) {
//        // TODO Auto-generated method stub
        try {
            System.out.println("how's the weather today?");
        } catch (Exception e) {
            System.out.println("i don't know");
        }finally{
            System.out.println("weather is fine");
        }

    Output:java

    how's the weather today?
    weather is fine测试

    这个你们都懂吧,我就不说什么了。code

    若是我加return的话,结果会怎么样?上测试代码:it

    

    public static void main(String[] args) {
//        // TODO Auto-generated method stub
        try {
            System.out.println("how's the weather today?");
            return;
        } catch (Exception e) {
            System.out.println("i don't know");
            return;
        }finally{
            System.out.println("weather is fine");
        }

    结果仍是:io

    how's the weather today?
    weather is fineclass

    

    代码走完,可能有些人得出结论:finally必定会执行。static

    不要着急,尚未完,再跑一段代码:co

    public static void main(String[] args) {
//        // TODO Auto-generated method stub
        try {
            System.out.println("how's the weather today?");
            System.exit(0);
        } catch (Exception e) {
            System.out.println("i don't know");
        }finally{
            System.out.println("weather is fine");
        }

    Output:return

    how's the weather today?void

    观看输出发现finally块并无被执行,JVM都退出了,还怎么运行呢。因此之后有人问的话,能够这样说,在JVM正常运行的状况下,finally块必定会执行。

相关文章
相关标签/搜索