JAVA Finally探究

来源:互联网 发布:外国人在淘宝买东西 编辑:程序博客网 时间:2024/06/10 09:16

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

     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 blockreturn statementfinally block :3
若是把finally中的return语句注释掉的话,则执行结果如下:

try blockreturn statementfinally block :3Exception in thread "main" java.lang.Exception: test :2at 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

0 0
原创粉丝点击