java中的异常链

把捕获的异常包装成一个新的异常,在新的异常中添加对新的异常的引用,再把新异常抛出,就像是链式反应一样,这种就叫异常链。

代码实例:

public static void main(String[] args){

     ChainTest ct=new ChainTest();//创建chainTest实例

    try{

        ct.test2();      

}catch(Exception e){

    e.printStackTrace();

    }

}

public void test1()throws DrunkException{

  throw new DrunkException("喝车别开酒");

}

public void test2(){

   try{

       test1();

}catch (DrunkException e){

            RuntimeException newExc=new RuntimeException("司机一滴酒亲人两行泪");//含参构造器   

             newExc.initCause(e);//调用newExc的init方法,把捕获的DrunkException传进去

             throw newExc;//抛出新异常

      }

}

原文地址:https://www.cnblogs.com/Dantewuxin/p/5729681.html