Java异常处理中finally中的return会覆盖catch语句中的return语句

2023-04-20,,

Java异常处理中finally中的return会覆盖catch语句中的return语句和throw语句,所以Java不建议在finally中使用return语句

此外 finally中的throw语句也会覆盖catch语句中的return语句和throw语句

程序实例如下:(本代码来源于CSDN某大神:http://blog.csdn.net/hguisu/article/details/6155636   在此表示感谢)

package Test;  

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, finally; return value=false
testEx, finally; return value=false

此外:

finally块的语句在try或catch中的return语句执行之后返回之前执行且finally里的修改语句不能影响try或catch中 return已经确定的返回值(如果catch语句中返回的是一个引用,那么在finally语句中对引用的内容进行修改是会影响catch中return的返回值的),若finally里也有return语句则覆盖try或catch中的return语句直接返回。

Java异常处理中finally中的return会覆盖catch语句中的return语句的相关教程结束。

《Java异常处理中finally中的return会覆盖catch语句中的return语句.doc》

下载本文的Word格式文档,以方便收藏与打印。