What is NullPointerException and how to fix it?
P粉649990273
2023-08-23 10:22:08
<p>What are Null Pointer Exceptions (<code>java.lang.NullPointerException</code>) and what cause them? </p>
<p>What methods/tools can be used to determine the cause so that the exception can be prevented from causing the program to terminate prematurely? </p>
The fastest example code I can think of to illustrate NullPointerException is probably:NullPointerException
is an exception that occurs when you try to use a reference to any location in memory (null), just like a reference to an object. Calling a method on a null reference or trying to access a field with a null reference will trigger aNullPointerException
. These are the most common, but other methods are listed in the NullPointerExceptionjavadoc page.
main
(This is a technical question, but I think it's worth mentioning: a reference to null is not the same as a C pointer pointing to an invalid memory location. A null pointer doesn't actually point to anywhere, unlike pointing to exactly one Invalid positions are slightly different.), I explicitly set the
Objectreference
objto
null. This means I have a reference, but it doesn't point to any object. Afterwards, I try to treat the reference as pointing to an object by calling its methods. This results in a
NullPointerExceptionbecause there is no code to execute at the location pointed to by the reference.
There are two main types of variables in Java:
Primitive: Variable containing data. If you want to manipulate the data in the original variable, you can manipulate the variable directly. By convention, primitive types begin with a lowercase letter. For example, variables of type
int
orchar
are primitives.Reference : A variable containing the memory address of the
object
, that is, a variable that references the object Code>. If you want To operate on theObject
referenced by a reference variable, you must dereference it. Dereferencing typically requires using.
to access a method or field, or[
to index an array. By convention, reference types are usually represented by the type starting with an uppercase letter. For example, variables of typeObject
are references.Consider the following code, in which you declare a
primitive
variable of type int but do not initialize it:These two lines will crash the program because no value has been specified for
x
and we are trying to use the value ofx
to specifyy
>. All primitives must be initialized to usable values before they can be manipulated.Now things get interesting. References variables can be set to
null
, which means "I'm not referencing anything". If you explicitly set a reference variable in this way, you can get anull
value in the reference variable, or the reference variable is not initialized and the compiler doesn't catch it (Java automatically sets the variable tonull
).If you set a reference variable to null, either explicitly or automatically via Java, and you try to dereference it, you will get a
NullPointerException
.A NullPointerException
Use the following code:(NPE) typically occurs when you declare a variable but do not create an object and assign it to the variable before trying to use the variable's contents. So you're referencing something that doesn't actually exist.
num
In the second line, the, but it doesn't actually contain a reference value yet. Since you haven't said what you want to point to, Java sets it to
null.
new
If you try to dereferencekeyword is used to instantiate (or create) an object of type
Integer, and the reference variable
numis assigned to the
IntegerObject.
num
For example, you might have a method like this:before creating the object,
, you will get a NullPointerException. In the simplest case, the compiler will catch the problem and let you know "
num may not have been initialized", but sometimes you may write code that doesn't create the object directly.
obj
In this case,but assume it was created before calling the
doSomething()method. Note that the method can be called like this:
obj
If the method is intended to perform some operation on the object passed in like the method above, it is appropriate to throwis
nulland the statement
obj.myMethod()will throw
NullPointerException>.
NullPointerException
because this is a programmer error and the programmer needs that information for debugging Purpose.
In addition to
NullPointerException
exceptions thrown due to method logic, you can also check fornull
values in method parameters and explicitly throw an NPE by adding something like: Followed near the beginning of the method:Note that it would be helpful to explicitly state which object cannot be
null
in the error message. The advantages of validating this are that 1) you can return your own clearer error message, 2) for the rest of the method you know that obj is not null unless it is reallocated and can be safely dereferenced.Alternatively, in some cases, the purpose of the method is not just to operate on the object passed in, so an empty parameter may be acceptable. In this case you need to check for null arguments and behave differently. You should also explain this in the documentation. For example,
doSomething()
can be written as:Finally, How to use stack traces to pinpoint exceptions and causes
Sonar with the Find Error feature can detect NPE. Can sonar dynamically capture null pointer exceptions caused by JVM一个>
Now Java 14 adds a new language feature to show the root cause of NullPointerException. This language feature has been part of the SAP Business JVM since 2006.
In Java 14, the following is an example NullPointerException exception message:
List of situations that lead to
NullPointerException
The following are all situations in which a
NullPointerException
is directly mentioned by the Java Language Specification:Throws null value;
synchronized (someNullReference) { ... }
NullPointerException
NullPointerException
.super
on a null reference will throwNullPointerException
. If you're confused, this is talking about qualified superclass constructor calls:Use
for (element : iterable)
loop to loop through an empty collection/array.switch (foo) { ... }
(whether an expression or a statement) can throwNullPointerException
whenfoo
is empty .foo.new SomeInnerClass()
ThrowsNullPointerException
whenfoo
is null.
The comment from JLS states thatname1::name2
orprimaryExpression::name
will throwNullPointerException
name1# when evaluated in the following cases ## or primaryExpressionevaluates to null.
someInstance.someStaticMethod()
does not throw an NPE because
someStaticMethodis static, but
someInstance::someStaticMethodstill Throw NPE!
* Please note that JLS may also indirectly talk a lot about NPE.