• 异常链


    场景: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");
    
            }
        }
    }

    修改后的运行结果:

    总结:

  • 相关阅读:
    Vue3手册译稿
    Vue3手册译稿
    Vue3手册译稿
    Vue3手册译稿
    Vue3手册译稿
    Vue3手册译稿
    C# 多线程与异步的使用方法笔记
    PetaPoco 5.1.306 的生成模板加注释
    RichEditDocumentServer打印记录
    RichEditDocumentServer 打印份数
  • 原文地址:https://www.cnblogs.com/mpp0905/p/10367599.html
Copyright © 2020-2023  润新知