00:00

Helpful NullPointerExceptions in Java (Since Java 14)

Last updated: · Standard since Java 14

Since Java 14 (JEP 358), a NullPointerException message explains which action failed and which expression was null, for example Cannot read field "nickname" because "...profile" is null. The feature was enabled by default in Java 15, so every Java 17 application benefits from it.

This tutorial shows the kinds of messages you will see, why some show placeholders such as <local1>, and how to control the feature.

1. Why Were Helpful NPE Messages Added?

Before Java 14 a NullPointerException had no message, only a line number. In a chain such as a.b().c.d() you could not tell which reference was null without a debugger. The JVM already knows exactly which bytecode failed, so JEP 358 makes it describe the problem.

2. Controlling the Feature

OptionEffect
(default since Java 15)detailed messages are on
-XX:-ShowCodeDetailsInExceptionMessagesturns detailed messages off
-XX:+ShowCodeDetailsInExceptionMessagesturns them on (needed in Java 14)
javac -gincludes local variable names, so messages show city instead of <local1>

3. Practical Examples

Example 1: Messages for fields, method calls and arrays

NpeMessages.java
import java.util.HashMap;
import java.util.Map;

public class NpeMessages {
    static class Profile { String nickname; }
    static class User { Profile profile; }

    static Map<String, User> users = new HashMap<>();
    static int[][] matrix = new int[3][];         // inner arrays not created yet
    static String[] names;                        // never assigned

    public static void main(String[] args) {
        users.put("u1", new User());               // profile is null

        run(() -> users.get("u1").profile.nickname.length());
        run(() -> users.get("u2").profile.toString());

        run(() -> System.out.println(matrix[2][0]));
        run(() -> System.out.println(names.length));
    }

    static void run(Runnable action) {
        try {
            action.run();
        } catch (NullPointerException e) {
            System.out.println(e.getMessage());
        }
    }
}
Output
Cannot read field "nickname" because "java.util.Map.get(Object).profile" is null
Cannot read field "profile" because the return value of "java.util.Map.get(Object)" is null
Cannot load from int array because "NpeMessages.matrix[2]" is null
Cannot read the array length because "NpeMessages.names" is null

The first message names the full chain, so you know immediately that profile was null, not nickname.

Example 2: Local variable names and the -g option

LocalNames.java
public class LocalNames {
    public static void main(String[] args) {
        String city = null;
        try {
            System.out.println(city.toUpperCase());
        } catch (NullPointerException e) {
            System.out.println(e.getMessage());
        }
    }
}
Output
Cannot invoke "String.toUpperCase()" because "<local1>" is null

Compile and run: javac LocalNames.java && java LocalNames

Command: javac -g LocalNames.java && java LocalNames

Output
Cannot invoke "String.toUpperCase()" because "city" is null

Command: java -XX:-ShowCodeDetailsInExceptionMessages LocalNames

Output
null

Without debug information, the JVM does not know local variable names and prints <local1>. With the feature disabled, the message is null, as in old Java versions.

4. How the Message Is Built

Building a helpful NPE message When an instruction dereferences null, the JVM analyses the bytecode to find the failed action and the expression that produced null, then builds the message lazily when getMessage is called. null dereference getfield / invoke bytecode analysis find the source expression names fields, methods, locals with -g message built only when read
Figure 1: The message is computed only when getMessage() is called, so there is no cost for exceptions that are never inspected.

5. Important Points and Best Practices

  • Compile with -g (Maven and Gradle usually do this by default) to see local variable names.
  • Messages may reveal code structure; check your logging policy for sensitive systems.
  • A helpful message does not replace good design: validate inputs early with Objects.requireNonNull and use Optional for missing values.
  • Exceptions you create yourself with new NullPointerException() do not get the extra detail.

6. Summary

  • JEP 358 (Java 14) added detailed NullPointerException messages.
  • They are on by default since Java 15, so Java 17 has them.
  • Messages name the failed action and the null expression.
  • Compile with -g to include local variable names.

Related Tutorials

7. References