NullPointerException
may be thrown under several different scenarios. From the documentation:
Thrown when an application attempts to use null
in a case where an object is required. These include:
- Calling the instance method of a
null
object.
- Accessing or modifying the field of a
null
object.
- Taking the length of
null
as if it were an array.
- Accessing or modifying the slots of
null
as if it were an array.
- Throwing
null
as if it were a Throwable
value.
Applications should throw instances of this class to indicate other illegal uses of the null
object.
As with any exception, you should carefully examine the stack trace to see if there's any useful information about why it was thrown. If indeed it is caused by illegally accessing a null
reference as if it was a real object, then the general approach to debugging these kinds of problems is to to break up expressions like this:
// chained method invokations, can be hard to debug
var.method1().method2(arg).method3()
Into multiple statements like this:
// broken into multiple assignments
var1 = var.method1();
var2 = var1.method2();
var3 = var2.method3();
Now when a NullPointerException
occurs, you'll know the exact part of the chain that throws it, namely which var
is null
.
Identifying the where part quickly narrows the search for the why. If var
itself is null
, then trace it back to previous assignments. If varN
is null
, then look up the documentation for methodN()
to see under what circumstances can it return null
.
If the null
comes from a get
-type operation on a container/mutable data structure, then the problem is no longer as neatly localized, and you'll have to figure out where the corresponding set
happened. If null
is never a legal value for this container, then perhaps it should perform the null
-check during set
: it's always better to cause failure earlier rather than later, because the source of the bug can be localized more easily.
Related questions
On debugging NullPointerException
:
On application-specific behavior for throwing NullPointerException
:
On other NullPointerException
scenarios instructive for learning:
On null
itself: