有如下代码:
class Annoyance extends Exception {}
class Sneeze extends Annoyance {}
class Human {
public static void main(String[] args)
throws Exception {
try {
try {
throw new Sneeze();
}
catch ( Annoyance a ) {
System.out.println("Caught Annoyance");
throw a;
}
}
catch ( Sneeze s ) {
System.out.println("Caught Sneeze");
return ;
}
finally {
System.out.println("Hello World!");
}
}
}
经过测试输出如下结果:
Caught Annoyance
Caught Sneeze
Hello World!
按一般思路来说 throw a ,a 应该是Annoyance类型对象,不应该被第二个catch捕获了,但是实验结果证明被第二个catch捕获了。
会不会 catch 判断一个异常对象 是 通过 异常对象的运行时类型来判断的,a 的运行时类型是Sneeze ,如果是这样就能解释通了。
class Annoyance extends Exception {}
class Sneeze extends Annoyance {}
class Human {
public static void main(String[] args)
throws Exception {
try {
try {
throw new Sneeze();
}
catch ( Annoyance a ) {
System.out.println("Caught Annoyance");
//加了红色部分的测试语句
if(a instanceof Sneeze){
System.out.println("true");
}else{
System.out.println("false");
}
throw a;
}
}
catch ( Sneeze s ) {
System.out.println("Caught Sneeze");
return ;
}
finally {
System.out.println("Hello World!");
}
}
}
测试结果:
Caught Annoyance
true
Caught Sneeze
Hello World!
实验结果验证了上面的猜想,但是本人没有去查看源代码,故这还是一种猜想~~