Java:关于finally的说明

本文详细解析了Java中finally关键字在异常处理过程中的作用及特性,通过实例代码展示了finally块如何影响异常流控制,并揭示了其内部机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在异常处理时会使用finally关键字,那么大家可以看一下下面的代码

public class TestException {
    public TestException() {
    }

    boolean testEx() throws Exception {
        boolean ret = true;
        try {
            ret = testEx1();
        } catch (Exception e) {
            System.out.println("testEx, catch exception");
            ret = false;
            throw e;
        } finally {
            System.out.println("testEx, finally; return value=" + ret);
            return ret;
        }
    }

    boolean testEx1() throws Exception {
        boolean ret = true;
        try {
            ret = testEx2();
            if (!ret) {
                return false;
            }
            System.out.println("testEx1, at the end of try");
            return ret;
        } catch (Exception e) {
            System.out.println("testEx1, catch exception");
            ret = false;
            throw e;
        } finally {
            System.out.println("testEx1, finally; return value=" + ret);
            return ret;
        }
    }

    boolean testEx2() throws Exception {
        boolean ret = true;
        try {
            int b = 12;
            int c;
            for (int i = 2; i >= -2; i--) {
                c = b / i;
                System.out.println("i=" + i);
            }
            return true;
        } catch (Exception e) {
            System.out.println("testEx2, catch exception");
            ret = false;
            throw e;
        } finally {
            System.out.println("testEx2, finally; return value=" + ret);
            return ret;
        }
    }

    public static void main(String[] args) {
        TestException testException1 = new TestException();
        try {
            testException1.testEx();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

大家觉得输出结果是什么呢?

i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, catch exception
testEx1, finally; return value=false
testEx, catch exception
testEx, finally; return value=false

如果你得出的答案是上面所示,那么你错啦
正确答案是:

i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false

这是因为一旦finally中使用了return或throw语句,将会导致try块、catch块中的return、throw语句失效。
testEx2()方法中的catch块throw e;语句并没有执行,所以testEx1()并没有捕捉异常,testEx也没有捕捉异常。

(当java程序执行try块、catch块时遇到了return或throw语句,这两个语句会导致方法立即结束,所以系统并不会立即执行者两个语句,而是去寻找是否有finally块,如果没有,程序立即执行return或throw语句,方法终止;如果有finally,系统立即执行finall块,只有当finally块执行完成后系统才跳回来执行try、Catch块里的return、throw,如果finally里也使用了return或throw等导致方法终止的语句,则finally块已经终止了方法,系统将不会跳回执行try、catch块里的任何代码。)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值