Consider the below code:
String s = null;
s.toLowerCase();
It throws a NPE:
Exception in thread "main" java.lang.NullPointerException
at pracJava1.Prac.main(Prac.java:7)
The question is: Why can't the JVM also put a helper message saying:
Exception in thread "main" java.lang.NullPointerException. Attempted
toLowerCase() on null
This is useful in cases like obj.setName(s.toLowerCase())
, where the line number is not sufficient to guess if obj
was null or s
.
On the feasibility of it, lets look at the byte code generated:
stack=1, locals=2, args_size=1
0: aconst_null
1: astore_1
2: aload_1
3: invokevirtual #2 // Method java/lang/String.toLowerCase:()Ljava/lang/String;
So may be it does know, the method name it attempted the operation on. JVM experts, what's your opinion?
Why can't the JVM also put a helper message
First of all, JVM can do this. For example, SAP JVM indeed provides extended messages for NullPointerExceptions, ClassCastExceptions etc.
There were requests to do the same for HotSpot JVM, but they were closed as Will-Not-Fix for the reasons mentioned in @StephenC answer.
However, it is possible to enrich NullPointerException messages with the help of JVM TI agent.