java 异常匹配
抛出异常的时候,异常处理系统会安装代码书写顺序找出"最近"的处理程序. 找到匹配的程序后,它就认为异常将得到清理,然后就不再继续查找.
查找的时候并不要求抛出的异常同处理程序的异常完全匹配.派生类的对象也可以配备其基类的处理程序
package exceptions; //: exceptions/Human.java // Catching exception hierarchies. class Annoyance extends Exception {} class Sneeze extends Annoyance {} public class Human { public static void main(String[] args) { // Catch the exact type: try { throw new Sneeze(); } catch(Sneeze s) { System.out.println("Caught Sneeze"); } catch(Annoyance a) { System.out.println("Caught Annoyance"); } // Catch the base type: try { throw new Sneeze(); } catch(Annoyance a) { System.out.println("Caught Annoyance"); } } } /* Output: Caught Sneeze Caught Annoyance *///:~
换句话说,捕获基类的异常,就可以匹配所有派生类的异常
try { throw new Sneeze(); } catch(Annoyance a) { } catch(Sneeze s) { //这句编译器会报错,异常已由前面catch子句处理 }