JAVA异常处理之finally中最好不要使用return
2024-10-11 19:25:29
finally 语句块中, 最好不要使用return, 否则会造成已下后果;
1, 如果catch块中捕获了异常, 并且在catch块中将该异常throw给上级调用者进行处理, 但finally中return了, 那么catch块中的throw就失效了, 上级方法调用者是捕获不到异常的. 见demo如下:
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
尽管testEx2中的catch抛出异常, 但因为finally中return了, 那么testEx1中是捕获不到异常的, 所以testEx1中的catch块是不会执行的.
2, 如果在finally里的return之前执行了其它return , 那么最终的返回值是finally中的return:
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) {
}
}
}
输出结果为5, 5
如果finally中的return被注释掉, 那么输出结果是4, 5
最新文章
- C# VLCPlayer视频播放器(附源码)
- 如何动态在文档中加入<script></script>写入大段js?
- [问题2014A13] 解答
- 【poj3177】 Redundant Paths
- Photoshop笔记一
- VMware下LINUX的虚拟机增加磁盘空间
- BestCoder Round #85 sum
- bzoj 2152: 聪聪可可 树的点分治
- [Angular 2] Using the @Inject decorator
- Objective-C 关于静态方法与实例方法的转载
- docopt——好用的Python命令行参数解释器
- ●HDU 3507 Print Article
- [NOIP2017普及组]棋盘
- dubbo框架初步学习
- c#+.net常用功能点
- Linux comm命令求出文件的交集、差集
- L1与L2损失函数和正则化的区别
- 线程同步——用户模式下线程同步——Interlocked实现线程同步
- Table展开行
- PDFSharp生成PDF.