Adding info to an exception
Posted
by
NoozNooz42
on Stack Overflow
See other posts from Stack Overflow
or by NoozNooz42
Published on 2010-12-31T04:15:35Z
Indexed on
2010/12/31
4:54 UTC
Read the original article
Hit count: 421
I'd like to add information to a stack trace/exception.
Basically I've got something like this as of now, which I really like:
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
However I'd like to catch that exception and add additional info to it, while still having the original stack trace.
For example, I'd like to have that:
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
So basically I want to catch the ArithmeticException and rethrow, say, a CustomException (adding "you tried to divide 42 by 0" in this example) while still keeping the stacktrace from the original ArithmeticException.
What is the correct way to do this in Java?
Is the following correct:
try {
....
} catch (ArithmeticException e) {
throw new CustomException( "You tried to divide " + x + " by " + y, e );
}
© Stack Overflow or respective owner