public class TestException {
public static void main(String args[]) {
TestException test = new TestException();
try {
test.testA();
}catch(Exception e) {
System.out.println("A has been got");
}
try {
test.testB();
}catch(Exception ex) {
System.out.println("B has been got");
}
}
public void testA() {
try {
int a = 1;
int b = 0;
int c = a/b;
}catch(Exception ex) {
System.out.println("interesting.");
throw ex;
}finally {
System.out.println("in B,I am sure that I can work.");
}
}
public void testB(){ //这一行如果不改成 public void testB() throws Exception 则编译必然不通过
try {
int a=1;
int b=0;
int c = a/b;
}catch(Exception e) {
throw new Exception();
}
}
}
不管怎么说两个方法都存在抛出行为,为何 New 一个新的异常就必须如此定义呢...
谢谢
1
lzdhlsc 2018-03-24 08:23:58 +08:00 1
https://docs.oracle.com/javase/8/docs/technotes/guides/language/catch-multiple.html#rethrow
In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions: The try block is able to throw it. There are no other preceding catch blocks that can handle it. It is a subtype or supertype of one of the catch clause's exception parameters. 我的猜测是在 testB 中的 new Exception() 不是 try block throw 出来的, 所以上述 rethrow 机制没有生效。 |