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

最新文章

  1. C# VLCPlayer视频播放器(附源码)
  2. 如何动态在文档中加入<script></script>写入大段js?
  3. [问题2014A13] 解答
  4. 【poj3177】 Redundant Paths
  5. Photoshop笔记一
  6. VMware下LINUX的虚拟机增加磁盘空间
  7. BestCoder Round #85 sum
  8. bzoj 2152: 聪聪可可 树的点分治
  9. [Angular 2] Using the @Inject decorator
  10. Objective-C 关于静态方法与实例方法的转载
  11. docopt——好用的Python命令行参数解释器
  12. ●HDU 3507 Print Article
  13. [NOIP2017普及组]棋盘
  14. dubbo框架初步学习
  15. c#+.net常用功能点
  16. Linux comm命令求出文件的交集、差集
  17. L1与L2损失函数和正则化的区别
  18. 线程同步——用户模式下线程同步——Interlocked实现线程同步
  19. Table展开行
  20. PDFSharp生成PDF.

热门文章

  1. Jmeter-WINDOWS下的配置部署
  2. Spring mvc 中使用 kaptcha 验证码
  3. word和.txt文件转html 及pdf文件, 使用poi jsoup itext心得
  4. EntityFramework连接SQLite
  5. php后台模板html拼接写法
  6. php防止浏览器点击返回按钮重复提交数据
  7. selenium及webdriver的原理
  8. Java 9 揭秘(6. 封装模块)
  9. mysql 左连接 右连接 内链接
  10. 在jupyter notebook中同时安装python2和python3