Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java tell you which pointer is null?

I've always wondered why the JVM doesn't tell you which pointer (or more precisely, which variable) is null when a NullPointerException is thrown.

A line number isn't specific enough because the offending line can often contain numerous variables that could have caused the error.

Is there any compiler or JVM flag that would make these exception messages more useful?

like image 519
kpozin Avatar asked Jul 22 '09 21:07

kpozin


People also ask

Why do we get NullPointerException in Java?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

What is != null in Java?

Null is not an instance of any class. Hence a null value will return false if used with the instanceOf operator. Static methods are callable with a reference of the null type. You cannot call non-static methods with a reference of the null type. You can use == and !=

What is Java Lang NullPointerException error?

The java. lang. NullPointerException is an error in Java that occurs as a Java program attempts to use a null when an object is required. The NullPointerException is a public class that extends the RuntimeException.


1 Answers

It's because the dereference always happens when there is no name available. The value is loaded onto the operand stack, and is then passed to one of the JRE opcodes that dereferences it. However, the operand stack does not have a name to associate with a null value. All it has is 'null'. With some clever runtime tracking code, a name can be derived, but that would add overhead with limited value.

Because of this, there is no JRE option that will turn on extra information for null pointer exceptions.

In this example, the reference is stored in local slot 1, which maps to a local variable name. But the dereference happens in the invokevirtual instruction, which only sees a 'null' value on the stack, and then throws an exception:

15 aload_1 16 invokevirtual #5  

Equally valid would be an array load followed by a dereference, but in this case there is no name to map to the 'null' value, just an index off of another value.

76 aload    5 78 iconst_0 79 aaload 80 invokevirtual #5 

You can't allocate the names statically to each instruction either - this example produces a lot of bytecode, but you can see that the dereference instruction will receive either objA or objB, and you would need to track this dynamically to report the right one, as both variables flow to the same dereference instruction:

(myflag ? objA : objB).toString() 
like image 131
Michael Donohue Avatar answered Oct 06 '22 07:10

Michael Donohue