题目一
// 已知
class ExampleA extends Exception;
class ExampleB extends ExampleA ;
// 请问以下代码的打印结果
try{
throw new ExampleB("B");
}catch (ExampleA a){
System.out.println("ExampleA");
}catch (Exception e){
System.out.println("Exception");
}
答案:输出 :ExampleA
解析:根据 里氏代换 原则 [能使用父类型 的地方一定能使用子类型 ], 抓取 ExampleA 类型异常的catch块能够抓住try块中抛出的 ExampleB类型的异常 )
题目二
// 已知
class Annoyance extends Exception
class Sneeze extends Annoyance
// 请问以下代码的打印结果
public 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!");
}
}
}
答案:
Catch Annoyance
Catch Sneeze
Hello World!