Java:关于finally的说明

来源:互联网 发布:nginx tomcat 宕机 编辑:程序博客网 时间:2024/06/05 04:01

我们在异常处理时会使用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=2i=1testEx2, catch exceptiontestEx2, finally; return value=falsetestEx1, catch exceptiontestEx1, finally; return value=falsetestEx, catch exceptiontestEx, finally; return value=false

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

i=2i=1testEx2, catch exceptiontestEx2, finally; return value=falsetestEx1, finally; return value=falsetestEx, 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块里的任何代码。)

0 0
原创粉丝点击