Java NullPointerException

Of all the RuntimeExceptionexceptions, Java programmers are probably most familiar with NullPointerException.

NullPointerException is the null pointer exception, commonly known as NPE. This exception is usually thrown by the JVM if an object is null called, its methods are called or its fields are accessed , for example:NullPointerException

The concept of pointers is actually derived from the C language, and there are no pointers in the Java language. The variables we define are actually references, Null Pointer is more precisely Null Reference, but the difference between the two is not much.

Handling NullPointerException

If encountered NullPointerException, how should we deal with it? First of all, it must be clear that it NullPointerExceptionis a code logic error. When encountered NullPointerException, follow the principle of early exposure and early repair. It is strictly prohibited to use catchto hide such coding errors:

Good coding practices can greatly reduce NullPointerExceptionthe occurrence of, for example:

Member variables are initialized when they are defined:

A lot can be avoided by using an empty string ""instead of the default , and when writing business logic, it is much safer to use an empty string for unfilled .nullNullPointerException""null

Returns an empty string "", an empty array instead of null:

This saves the caller from having to check whether the result is null.

If the caller must make nulljudgments, such as returning to nullindicate that the file does not exist, then consider returning Optional<T>:

In this way, the caller must pass the Optional.isPresent()judgment whether there is a result.

Locating NullPointerException

If generated NullPointerException, for example, a.b.c.x()when called, the NullPointerExceptionreason may be:

  • ayes null;
  • a.byes null;
  • a.b.cyes null;

Determining exactly which object was nullpreviously only able to print logs like this:

Starting from Java 14, if generated NullPointerException, the JVM can give detailed information to tell us nullwho the object is. Let’s look at an example:

You can NullPointerExceptionsee similar in the details of ... because "<local1>" is null, meaning the cityfield is null, so we can quickly locate the problem.

This enhanced NullPointerExceptiondetail is new in Java 14, but is off by default, we can -XX:+ShowCodeDetailsInExceptionMessagesenable it by adding a parameter to the JVM:


NullPointerExceptionIt is a common logic error in Java code, which should be exposed and repaired early;

NullPointerExceptionDetailed error information can be viewed by enabling Java 14’s Enhanced Exception Information.