YaoDeBiAn
2017-03-11 11:22Java关于在catch中抛出一个异常给外围函数却捕获不到的问题
先给出一串代码:
package javaException;
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) {
// TODO Auto-generated method stub
TestException testException1=new TestException();
try{
testException1.testEx();
}
catch(Exception e){
e.printStackTrace();
}
}
}
对于函数testEx2()中catch块中抛出的异常,testEx1()函数却捕获不到,这是为什么呢?
我想过一种可能:testEx1()中将testEx2()的返回值赋值给ret,即 ret=testEx2(),而testEx2()中抛出的异常在这个过程中被过滤掉了。因为如果我直接把testEx2()放在testEx1()中,而不是通过ret=testEx2()的方式,那么这个异常是能够被捕获的。
求证各位大佬!!!
- 点赞
- 回答
- 收藏
- 复制链接分享
2条回答
为你推荐
- 如何在某个顶层方便的捕获事件线程抛出的异常
- swing
- 0个回答
- C++ const 引用捕获异常为什么是正确的?
- 开发语言
- c++
- 2个回答
- 判断一个char数组是否真正的对象
- it技术
- 互联网问答
- IT行业问题
- 计算机技术
- 编程语言问答
- 0个回答
- C# 自定义异常的捕捉问题
- 自定义异常
- c#
- 6个回答
- 我这个只能捕获InputMismatchException异常,要想抛出该异常怎么写。
- java
- 1个回答
换一换