我想要向堆栈跟踪/异常中添加信息。
目前我的代码大致如下,我真的很喜欢它:
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 );
}