将信息添加到例外

时间:2010-12-31 04:15:35

标签: java exception

我想将信息添加到堆栈跟踪/异常。

基本上我现在有类似的东西,我非常喜欢:

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除以0”),同时仍然保持堆栈跟踪不受原始ArithmeticException的影响。

在Java中执行此操作的正确方法是什么?

以下是否正确:

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

2 个答案:

答案 0 :(得分:11)

是的,从Java 1.4开始,您可以在Java中嵌套类似的异常。我一直这样做。请参阅http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html

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

答案 1 :(得分:11)

你也可以这样做:

try {
     ....
} catch (ArithmeticException e) {
     ArithmeticException ae = new ArithmeticException( "You tried to divide " + x + " by " + y+" "+e.getMessage());
     ae.setStackTrace(e.getStackTrace());
     throw ae;
}

哪会给你“看不见的”例外:-)

更新[2012年9月27日]:

在Java 7中:另一个很酷的技巧是:

try {
    ...
} catch (ArithmeticException e) {
    e.addSuppressed(new ArithmeticException( "You tried to divide " + x + " by " + y));
    throw e;
}
相关问题