先给出一串代码:
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()的方式,那么这个异常是能够被捕获的。
求证各位大佬!!!