public class Test {
}
class Annoyance extends Exception {
}
class Sneeze extends Annoyance {
}
/* 9、类 ExampleA 继承 Exception,类 ExampleB 继承ExampleA。
有如下代码片断:
try {
throw new ExampleB("b")
} catch(ExampleA e){
System.out.println("ExampleA");
} catch(Exception e){
System.out.println("Exception");
}
输出:ExampleA。(根据里氏代换原则[能使用父类型的地方一定能使用子类型],
抓取 ExampleA 类型异常的 catch 块能够抓住 try 块中抛出的 ExampleB 类型的异常)
*/
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类型的
//但是为什么?上面的里氏代换原则,父类能出现的地方,子类一定出现
} catch ( Sneeze s ) {
System.out.println("Caught Sneeze");
return ;
} finally {
System.out.println("Hello World!");
}
}
}
ACAC 异常(里氏代换原则)
猜你喜欢
转载自blog.csdn.net/qq_44707513/article/details/110228792
今日推荐
周排行