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

JAVA异常处理之finally中最好不要使用return

2017-03-24 12:58 495 查看
finally 语句块中, 最好不要使用return, 否则会造成已下后果;

1, 如果catch块中捕获了异常, 并且在catch块中将该异常throw给上级调用者进行处理, 但finally中return了, 那么catch块中的throw就失效了, 上级方法调用者是捕获不到异常的. 见demo如下:

public class TestException3 {
public static int x = 3;
int testEx() throws Exception {
try {
x = 4;
return x;
} catch (Exception e) {

} finally {
x = 5;
return x;
}
}
public static void main(String[] args) {
TestException3 testException3 = new TestException3();
try {
int a = testException3.testEx();
System.out.println(a);
System.out.println(x);
} catch (Exception e) {
}
}
}


View Code
输出结果为5, 5

如果finally中的return被注释掉, 那么输出结果是4, 5
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: