Java:关于finally的说明
2015-11-09 12:53
651 查看
我们在异常处理时会使用finally关键字,那么大家可以看一下下面的代码
大家觉得输出结果是什么呢?
如果你得出的答案是上面所示,那么你错啦
正确答案是:
这是因为一旦finally中使用了return或throw语句,将会导致try块、catch块中的return、throw语句失效。
testEx2()方法中的catch块throw e;语句并没有执行,所以testEx1()并没有捕捉异常,testEx也没有捕捉异常。
(当java程序执行try块、catch块时遇到了return或throw语句,这两个语句会导致方法立即结束,所以系统并不会立即执行者两个语句,而是去寻找是否有finally块,如果没有,程序立即执行return或throw语句,方法终止;如果有finally,系统立即执行finall块,只有当finally块执行完成后系统才跳回来执行try、Catch块里的return、throw,如果finally里也使用了return或throw等导致方法终止的语句,则finally块已经终止了方法,系统将不会跳回执行try、catch块里的任何代码。)
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, catch exception testEx1, finally; return value=false testEx, catch exception testEx, finally; return value=false
如果你得出的答案是上面所示,那么你错啦
正确答案是:
i=2 i=1 testEx2, catch exception testEx2, finally; return value=false testEx1, finally; return value=false testEx, finally; return value=false
这是因为一旦finally中使用了return或throw语句,将会导致try块、catch块中的return、throw语句失效。
testEx2()方法中的catch块throw e;语句并没有执行,所以testEx1()并没有捕捉异常,testEx也没有捕捉异常。
(当java程序执行try块、catch块时遇到了return或throw语句,这两个语句会导致方法立即结束,所以系统并不会立即执行者两个语句,而是去寻找是否有finally块,如果没有,程序立即执行return或throw语句,方法终止;如果有finally,系统立即执行finall块,只有当finally块执行完成后系统才跳回来执行try、Catch块里的return、throw,如果finally里也使用了return或throw等导致方法终止的语句,则finally块已经终止了方法,系统将不会跳回执行try、catch块里的任何代码。)
相关文章推荐
- Java集合框架体系
- Java记录 -72- Vector,HashTable和Properties
- Mac OS X下安装Java 7及配置Eclipse JDK
- Spring MVC异常处理详解(转)
- java作业6
- java 入门 第二季3
- hibernate+spring处理BLOB,CLOB字段
- java判断字符串是否为数字的方法小结
- Java中String.intern()方法详解
- 怎么学习Java
- Java枚举enum
- 快排,堆排序,折半查找算法(Java版)
- java 双击jar包操作
- Spring AOP 实现原理
- Java 通过JDBC连接Mysql数据库
- eclipse重新设置workspace路径
- Java 中 synchronized的用法详解(四种用法)
- J2EE spring日志
- Not able to find Java executable or version. Pleas
- Java Code To Byte Code