Java中的finally代码块一定会被执行吗?

先说结论: Java中的finally代码块不一定会被执行。

下面具体分析一下finally代码块不会被执行的两种情况。

情况1:当代码在try语句之前结束运行时,finally代码块不会被执行

换句话说,当try代码块得不到执行时,相应的finally块也不会被执行。例如,当程序在try语句之前就return时,finally代码块就不会被执行,详情见下面代码示例及输出结果。

public class FinallyTest {
    public static void main(String[] args) {
        int i = 0;
        if (i == 0) {
            return;
        }

        try {
            System.out.println("this is try ...");
        } catch (Exception e) {
            System.out.println("this is catch ...");
        } finally {
            System.out.println("this is finally ...");
        }
    }
}

程序输出:

Process finished with exit code 0

情况2:当执行try语句块的线程终止时,finally代码块不会被执行

当在try语句块里执行了System.exit()或者该线程被中断被kill,这些情况也会使得finally代码块得不到执行,详情见下面代码示例及输出结果。

public class FinallyTest {
    public static void main(String[] args) {
        int i = 0;

        try {
            System.out.println("this is try ...");
            System.exit(0);
        } catch (Exception e) {
            System.out.println("this is catch ...");
        } finally {
            System.out.println("this is finally ...");
        }
    }
}

程序输出:

this is try ...

Process finished with exit code 0

上面是finally代码块不会被执行的两种情况,下面本文介绍一下try_catch_finally和return的执行顺序问题。也就是说,除了上面两种情况,finally块是都会被执行的,问题在于何时被执行。

先说结论:finally块的执行时间点在try和catch中return语句的表达式值计算之后返回之前。 不论try和catch代码块中有没有return语句,执行顺序都是先计算try或catch中return语句的表达式的值并暂存,然后执行finally代码块。若finally代码块中无return,则返回之前try或catch中暂存的return语句的表达式的值;若finally代码块中有return,则直接就地返回。

请看下面的代码示例:

public class FinallyTest {
    public static void main(String[] args) {
        System.out.println("the result of test is: " + test());
    }

    private static int test() {
        int i = 0;

        try {
            i++;
            System.out.println("this is try ...");
            System.out.println("the value of i is: " + i);
            return calc(i);
        } catch (Exception e) {
            System.out.println("this is catch ...");
        } finally {
            i++;
            System.out.println("this is finally ...");
            System.out.println("the value of i is: " + i);
        }

        return i;
    }

    private static int calc(int i) {
        System.out.println("this is calc ...");
        System.out.println("the value of i is: " + i);
        return i;
    }
}

根据之前所述结论,test方法的返回值应当是1,你猜对了吗?程序运行结果如下:

this is try ...
the value of i is: 1
this is calc ...
the value of i is: 1
this is finally ...
the value of i is: 2
the result of test is: 1

Process finished with exit code 0

每日学习笔记,写于2020-04-19 星期日

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容