微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 向异常添加信息

我想向堆栈跟踪/异常添加信息.

基本上我现在有这样的东西,我真的很喜欢:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.so.main(SO.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke

但是,我想捕获该异常并添加其他信息,同时仍然具有原始堆栈跟踪.

例如,我想要这样做:

Exception in thread "main" CustomException: / by zero (you tried to divide 42 by 0)
    at com.so.main(SO.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke

所以基本上我想抓住ArithmeticException并重新抛出,比如说,一个CustomException(添加“你试图在这个例子中划分42”),同时仍然保持堆栈跟踪从原来的ArithmeticException.

在Java中做什么正确的方法

以下是正确的:

try {
     ....
} catch (ArithmeticException e) {
     throw new CustomException( "You tried to divide " + x + " by " + y,e );
}

解决方法

是的,您可以像Java 1.4中一样在Java中嵌套异常.我一直都这样做见 http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html.

当有人从您的自定义异常中打印堆栈跟踪时,它将显示嵌套ArithmeticException的CustomException堆栈跟踪和堆栈跟踪.你可以任意深入地嵌套.

原文地址:https://www.jb51.cc/java/125051.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐