问题描述
|
我正在检查我的程序的输出,在该输出中,有时会看到类似“ java.lang.NullPointerException \”的消息,而没有其他消息。因为这不是我的代码,所以我很确定,有一些3rd party库,其中有些混蛋做了类似的事情:catch(ex){println ex.getMessage()}。
有没有一种方法可以重新启用堆栈跟踪报告,并查看发生问题的位置?通过调试器+分步执行来执行此操作并不容易,因为问题是随机发生的,当我在大量输入数据上运行程序时,如果尝试重新输入则无法重现-在看起来有罪的数据切片上运行。
提前致谢!
解决方法
更新:您最好使用发现的IDE断点。
否则,您可以通过
System.setOut(..)
设置自定义PrintStream
,并且在此打印任何内容时,也要打印Thread.currentThread().getStackTrace()
。
理想情况下,您的PrintStream
应该只包装原始的System.out
并将其分发。就像是:
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);
}
}
然后,在程序开始时:
System.setOut(new PrintStreamWrapper(System.out));
, 不看代码,很难说。如果经常抛出异常,则HotSpot编译器实际上可能会优化周围的代码,以致VM无法生成正确的堆栈跟踪,并且Exception#printStackTrace()仅会打印异常的类名和消息。
在执行其他操作之前,我将尝试使用-XX:-OmitStackTraceInFastThrow VM参数运行您的应用程序,以强制VM为所有异常创建正确的堆栈跟踪。