不知道该问题别人提过没,不明白,求解。
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() {
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"+e.toString());
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) {
System.out.println("main"+e.getMessage());
e.printStackTrace();
}
}
}
运行的结果是i=2
i=1
testEx2, catch exceptionjava.lang.ArithmeticException: / by zero
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false
为什么testEx(),testEx1()中的catch没有运行,为什么没有捕捉到异常,testEx2()中不是把异常抛出来了吗?为什么testEx1()捕捉不到?
|
|