我已经有我们的Java代码的实例捕捉一个NullPointerException,但当我试图记录StackTrace(基本上最终调用Throwable.printStackTrace()),我得到的是:
java.lang.NullPointerException
有人遇到过吗?我试着在谷歌上搜索“java空指针空堆栈跟踪”,但没有遇到这样的东西。
我已经有我们的Java代码的实例捕捉一个NullPointerException,但当我试图记录StackTrace(基本上最终调用Throwable.printStackTrace()),我得到的是:
java.lang.NullPointerException
有人遇到过吗?我试着在谷歌上搜索“java空指针空堆栈跟踪”,但没有遇到这样的东西。
当前回答
(您的问题仍然不清楚您的代码是否调用printStackTrace()或这是由日志处理程序完成的。)
以下是一些可能的解释:
The logger / handler being used has been configured to only output the exception's message string, not a full stack trace. Your application (or some third-party library) is logging the exception using LOG.error(ex); rather than the 2-argument form of (for example) the log4j Logger method. The message is coming from somewhere different to where you think it is; e.g. it is actually coming some third-party library method, or some random stuff left over from earlier attempts to debug. The exception that is being logged has overloaded some methods to obscure the stacktrace. If that is the case, the exception won't be a genuine NullPointerException, but will be some custom subtype of NPE or even some unconnected exception.
我认为最后一种可能的解释是不太可能的,但人们至少会考虑做这种事情来“防止”逆向工程。当然,它只会让诚实的开发者的生活变得困难。
其他回答
(您的问题仍然不清楚您的代码是否调用printStackTrace()或这是由日志处理程序完成的。)
以下是一些可能的解释:
The logger / handler being used has been configured to only output the exception's message string, not a full stack trace. Your application (or some third-party library) is logging the exception using LOG.error(ex); rather than the 2-argument form of (for example) the log4j Logger method. The message is coming from somewhere different to where you think it is; e.g. it is actually coming some third-party library method, or some random stuff left over from earlier attempts to debug. The exception that is being logged has overloaded some methods to obscure the stacktrace. If that is the case, the exception won't be a genuine NullPointerException, but will be some custom subtype of NPE or even some unconnected exception.
我认为最后一种可能的解释是不太可能的,但人们至少会考虑做这种事情来“防止”逆向工程。当然,它只会让诚实的开发者的生活变得困难。
另一个建议——如果您正在使用Eclipse,您可以在NullPointerException本身上设置一个断点(在Debug透视图中,转到“Breakpoints”选项卡并单击有一个!在它)
检查“caught”和“uncaught”选项-现在当你触发NPE时,你会立即断点,然后你可以逐步查看它是如何被处理的,以及为什么你没有得到堆栈跟踪。
VM停止输出多次抛出的异常的堆栈跟踪。这是发生在C2编译中的优化之一。
根据OpenJDK源代码,此优化应用于以下例外情况:
nullpointerexception -ArithmeticException -ArrayIndexOutOfBoundsException -ArrayStoreException classcastexception
正如您在评论中提到的,您正在使用log4j。我(无意中)发现了一个我写过东西的地方
LOG.error(exc);
而不是典型的
LOG.error("Some informative message", e);
因为懒惰,或者可能只是没有想过。不幸的是,它的行为并不如您所期望的那样。记录器API实际上将Object作为第一个参数,而不是字符串——然后它对该参数调用toString()。因此,它没有得到漂亮的堆栈跟踪,只是打印出toString——在NPE的情况下,这是非常无用的。
也许这就是你正在经历的?
这将输出异常,只用于调试,你应该更好地处理你的异常。
import java.io.PrintWriter;
import java.io.StringWriter;
public static String getStackTrace(Throwable t)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
}