Skip to main content
Java 14 · Topic 2 of 2

Helpful NullPointerException messages

Definition​

Since Java 14 (on by default from Java 15) a NullPointerException tells you exactly which part was null, for example "because the return value of Demo.findCity() is null". You no longer have to guess in a long chain of calls.

Example code​

The exception now names the null part

class Demo {
static String findCity() { return null; }

public static void main(String[] args) {
try {
System.out.println(findCity().length());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
}
}

// Output:
// Cannot invoke "String.length()" because the return value of "Demo.findCity()" is null

Finished this page? Track your progress (saved only in your browser).