首页 > 编程语言 > 详细

java 异常匹配

时间:2019-01-22 13:57:19      阅读:198      评论:0      收藏:0      [点我收藏+]

   抛出异常的时候,异常处理系统会安装代码书写顺序找出"最近"的处理程序. 找到匹配的程序后,它就认为异常将得到清理,然后就不再继续查找.

  查找的时候并不要求抛出的异常同处理程序的异常完全匹配.派生类的对象也可以配备其基类的处理程序

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子句处理
    }

 

java 异常匹配

原文:https://www.cnblogs.com/jiangfeilong/p/10303212.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!