'Tracking "hidden" exceptions
I am inspecting the output of a program of mine where from time to time I see a message like "java.lang.NullPointerException" and nothing else. Because this doesn't come from my code, I am pretty sure, there is some 3rd party library, where some jerk has done something like: catch ( ex ) { println ex.getMessage () }.
Is there a way to re-enable the reporting of the stack trace and see where the problem is happening? It's not easy to do this via a debugger + step-by-step execution, since the problem occurs at random, when I run the program over a big set of input data, while I cannot reproduce it if I try to re-run over the data slice that looks guilty.
Thanks in advance!
Solution 1:[1]
Update: You'd better use the IDE breakpoint-on-exception that you discovered.
Otherwise, you can set a custom PrintStream
via System.setOut(..)
and there, whenever something is printed, also print the Thread.currentThread().getStackTrace()
Ideally your PrintStream
should just wrap the original System.out
and dispatch to it. Something like:
public class PrintStreamWrapper extends PrintStream {
public PrintStreamWrapper(OutputStream out) {
super(out);
}
public void println(String x) {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
// print everything, but not to the System.out,
// because you'll end up in a loop.
super.println(x);
}
}
And then, in the beginning of your program:
System.setOut(new PrintStreamWrapper(System.out));
Solution 2:[2]
Without seeing the code, it is difficult to say. If an exception is thrown frequently, the HotSpot compiler may actually optimize the surrounding code so much, that the VM is not able to generate a proper stack trace and Exception#printStackTrace() will only print the exception's class name and message.
Before doing anything more, I would try to run your application with the -XX:-OmitStackTraceInFastThrow VM argument to force the VM to create a proper stack trace for all exceptions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Anish B. |
Solution 2 | jarnbjo |