您的位置:首页 > 编程语言 > Java开发

Java:关于finally的说明

2015-11-09 12:53 651 查看
我们在异常处理时会使用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块里的任何代码。)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: