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堆栈跟踪和堆栈跟踪.你可以任意深入地嵌套.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...