e 是 Exception 类型,但在下面的代码中打印 Exception1:
class Exception1 extends IOException {void info(){}}
class Exception2 extends Exception {}
class TestMultiCatch {
public static void main(String args[]) {
try {
int a = 10;
if (a <= 10)
throw new Exception1();
else
throw new Exception2();
} catch (Exception1 | Exception2 e) {
e.info(); //line 1 error "The method info() is undefined for type Exception"
System.out.println(e); //prints Exception1 (after commenting line 1)
}
}
}
根据我的研究,“e”应该是 Exception 类型,它是 Exception1 和 Exception2 的通用基类。从第 1 行的消息中可以明显看出。
但是为什么:
System.out.println(e); //prints Exception1 and not Exception
System.out.println(e instanceof IOException); //prints true and not false
System.out.println(e instanceof Exception1); //prints true and not false
System.out.println(e instanceof Exception2); //false
? 谢谢。