zoukankan      html  css  js  c++  java
  • java异常丢失及异常链

     1.Java中异常丢失的情况:

      先定义三个异常:

    public class ExceptionA extends Exception {
        public ExceptionA(String str) {
            super();
        }
    }
     
    public class ExceptionB extends ExceptionA {
     
        public ExceptionB(String str) {
            super(str);
        }
    }
     
    public class ExceptionC extends ExceptionA {
        public ExceptionC(String str) {
            super(str);
        }
    }

      接着定义一个测试类:

    public class NeverCaught {
        static void f() throws ExceptionB{
            throw new ExceptionB("exception b");
        }
     
        static void g() throws ExceptionC {
            try {
                f();
            } catch (ExceptionB e) {
                ExceptionC c = new ExceptionC("exception a");
                throw c;
            }
        }
     
        public static void main(String[] args) {
                try {
                    g();
                } catch (ExceptionC e) {
                    e.printStackTrace();
                }
        }
     
    }

      输出的结果:

    exception.ExceptionC
    at exception.NeverCaught.g(NeverCaught.java:12)
    at exception.NeverCaught.main(NeverCaught.java:19)

      打印的异常信息中丢了ExceptionB的信息。如果希望能同时输出ExceptionB和ExceptionC的信息,就需要用到异常链。

      异常链主要作用就是:保存异常信息,在抛出另外一个异常的同时不丢失原来的异常。

     2.Java异常链的使用

      下面的代码将示例以两种方法实现异常链向上抛出异常。

    public class NeverCaught {
        static void f() throws ExceptionB{
            throw new ExceptionB("exception b");
        }
     
        static void g() throws ExceptionC {
            try {
                f();
            } catch (ExceptionB e) {
                ExceptionC c = new ExceptionC("exception a");
                //异常链
                c.initCause(e);
                //另外一种实现方式
           // throw new Exception("exception a", e);   
                throw c;
            }
        }
     
        public static void main(String[] args) {
                try {
                    g();
                } catch (ExceptionC e) {
                    e.printStackTrace();
                }
        }
     
    }

      需要注意的是:

      只有Error,Exception,RunimeException提供了带cause参数的构造器,其他的所以异常就只有通过initCause()来设置cause了。自己定义的异常提供了带cause参数的构造器时,也可以正常设置。

  • 相关阅读:
    #leetcode#Missing Ranges
    Redhat Crash Utility-Ramdump
    Android Touch事件传递机制具体解释 下
    POJ 2001 Shortest Prefixes 【 trie树(别名字典树)】
    分析cocos2d-x的lua项目中的工具方法
    #測试相关#Getting “junit.framework.AssertionFailedError: Forked Java VM exited abnormally” Exception
    POJ 题目3264 Balanced Lineup(RMQ)
    在Linux下安装R语言软件
    谷歌浏览器插件-html页面js事件查看器
    Map集合
  • 原文地址:https://www.cnblogs.com/lnlvinso/p/4433709.html
Copyright © 2011-2022 走看看