我想向堆栈跟踪/异常添加信息.
基本上我现在有这样的东西,我真的很喜欢:
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 );
}