异常链

场景:testone抛出一个异常,testtwo接受到testone的异常后抛出一个新异常,testthree接收到testtwo的异常后再抛出一个新异常

代码如下:

package com.mpp.test;

public class TryDemoFive {
    public static void main(String[] args) {
        try{
            testTree();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void testOne() throws HotelAgeException{
        throw  new HotelAgeException();
    }

    public static void testTwo() throws Exception{
        try {
            testOne();
        }catch (HotelAgeException e){
            throw new Exception("我是新产生的异常1");
        }
    }

    public static void testTree() throws Exception{
        try {
            testTwo();
        }catch (Exception e){
            throw new Exception("我是新产生的异常2");
        }
    }
}

运行结果只显示最后一个异常,造成异常的丢失

解决异常链路抛出过程中丢失异常信息的问题:

修改后的代码:

package com.mpp.test;

public class TryDemoFive {
    public static void main(String[] args) {
        try{
            testTree();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void testOne() throws HotelAgeException{
        throw  new HotelAgeException();
    }

    public static void testTwo() throws Exception{
        try {
            testOne();
        }catch (HotelAgeException e){
            throw new Exception("我是新产生的异常1",e);  //把testone中捕获的异常参数,加进来
        }
    }

    public static void testTree() throws Exception{
        try {
            testTwo();
        }catch (Exception e){
            Exception e1 = new Exception("我是新产生的异常2"); //新建一个异常对象
            e1.initCause(e);   //把testttwo中的异常加进来
            throw e1; //抛出异常
//            throw new Exception("我是新产生的异常2");

        }
    }
}

修改后的运行结果:

总结:

 

posted @ 2019-02-12 23:52  青青子佩-  阅读(206)  评论(0编辑  收藏  举报