Java异常处理中finally中的return会覆盖catch语句中的return语句
2016-07-28 21:43
465 查看
Java异常处理中finally中的return会覆盖catch语句中的return语句和throw语句,所以Java不建议在finally中使用return语句
此外 finally中的throw语句也会覆盖catch语句中的return语句和throw语句
程序实例如下:(本代码来源于CSDN某大神:http://blog.csdn.net/hguisu/article/details/6155636 在此表示感谢)
输出结果为:
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语句直接返回。
此外 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进阶(三十八)快速排序
- Java进阶(三十八)快速排序
- struts2.1的一个小bug
- spring 在启动服务器的时候报错 Could not open ServletContext resource [/WEB-INF/dispather-servlet.xml]
- Eclipse Plug-ins for Gradle: buildship 插件安装说明
- Log4j配置详解
- 用java内部类实现多重继承
- java算法——将字符串中的不同字符分类取出存放
- java算法——分解质因数
- java算法——打印100以内的素数
- Spring:源码解读Spring IOC原理
- java算法——打印水仙花数
- Java栈,队列,优先队列的使用
- java算法——遍历上级目录
- linphone-PresenceNote.java文件分析
- [模版]Java 文件读入(字符流) GZip压缩、解压缩String
- Java常用关键字(public,private,protected)
- java入门第一季_1.9_封装
- java日期
- java 内存模型(JMM)简介