JAVA Finally探究

在代码检查时,发现了这样一段类似的代码:

     public static void main(String[] args) throws Exception {
         System.out.println(getTestValue());
    }

    private static String getTestValue() throws Exception {
        String test = "我是原始值";
        try {
            boolean flage = true;
            if (flage) {
                throw new Exception("我是异常信息");
            }
        } catch (Exception e) {
            test = e.getMessage();
            throw e;
        } finally {
            System.out.println("我是finally信息");
             return test;
        }
    }

 

于是就有这样的问题 "throw e"会执行吗? 

实际测试的结果是:

我是finally信息
我是异常信息
很明显throw e没有执行.那么try,catch,finally的执行顺序是什么,一下一些简单的历史可以很好的说明:

public class Test1 {
    public static void main(String[] args) throws Exception {
        System.out.println(test());
    }

    public static String test() throws Exception {
        int i = 0;
        try {
            i++;
            System.out.println("try block");
            return test1();
        } catch (Exception e) {
            throw new Exception("test :" + (++i));
        } finally {
            i++;
            System.out.println("finally block :" + i);
            return "";
        }
    }

    public static String test1() throws Exception {
        System.out.println("return statement");
        boolean flag = true;
        if (flag) {
            throw new Exception(" exception info");
        }
        return "after return";
    }
}

执行结果如下

try block
return statement
finally block :3
若是把finally中的return语句注释掉的话,则执行结果如下:

try block
return statement
finally block :3
Exception in thread "main" java.lang.Exception: test :2
	at Test1.test(Test1.java:13)
	at Test1.main(Test1.java:3)
  输出的结果顺序可能有差异,但内容是一样的.

根据上几个简单的历史可以得出如下结论:

      1. finally语句块是在return语句和throw语句之前执行的.

      2. return test() 语句实际上等于 String res = test();  和 return res 两条语句. 同理 throw new Exception("")  实际上也是两条语句.

      3. 当finally代码块中有return语句时, 不会再执行 其他地方的return语句或throw 语句.


参考信息:

解析Java finally

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜗牛_snail

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值