I'm catching different kind of Exceptions in my method.
If the exception is a NullPointerException
, I'd like to add a message to the existing exception.
Is there a way to add a message to an existing NullPointerException? I can't just create a new Exception, because I need the stacktrace etc.
My idea was to just create a new Exception like that:
new Exception("the message", myNullPointer);
But then, the output isn't as I need it, because that way, my stacktrace looks like that:
java.lang.Exception:
...bla
...bla
But I need it to keep the NullPointerException like that:
java.lang.NullPointerException:
...bla
...bla
Also it's important to say that I haven't access to the part where the initial NullPointer is created. So I can't add a message at start.
Edit: I know I should avoid NPEs. But I have to influence about the thrown NPE. So I have to react.
As pointed out in the comments, this may not be a good idea, especially because null exception might arise out of situations you didn't expect.
Nevertheless, you can do exactly what you want like this:
try {
...potentially throws exceptions...
} catch (Exception e) {
RuntimeException re = new RuntimeException(e);
re.setStackTrace(e.getStackTrace());
throw re;
}