Skip to content
Advertisement

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!

Advertisement

Answer

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));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement