Вопрос

Unless, there is a code line like, throw new NullPointerException(); null pointers usually occur when an expression that turns out to be null is operated upon. So, my question is, why does the message for the null pointer not contain the expression which is returning null?

Это было полезно?

Решение

I don't know for sure, but I imagine that the reason is that there could be major performance issues if the JVM had to be able to report the precise expression that threw the exception.

At the very least, it would require changes to the class file format to include (really) fine grained source code position information ... finer grained than line numbers.

Anyway, the question is moot ... 'cos it doesn't.

Другие советы

NullPointerException occurs when you try to dereference a null, not when you just create or have one. Stack trace contains the line, and that's as good as it gets, and JVM does not really know where the null came from, it does not keep track of such things when it tries to churn through the bytecode as fast as possible.


If you have trouble debugging such situations, you can always split expression and use temp variable:

String tmp = myObj.getSomething();
String result = tmp.substring(1);

If 1st line above throws NullPointerException (with stack trace showing it came from that line, not from inside myObj.getSomething()), you know myObj was null. If 2nd line throws NullPointerException, you know tmp was null, ie myObj.getSomething() returned null. If you then notice that myObj.getSomething() may in fact return null in normal situation, you can then add if (tmp != null) { ... } else { ... } kind of code there.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top