GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Helpful NullPointerExceptions | java.evolved

Home / Errors / Helpful NullPointerExceptions
Errors Beginner

Helpful NullPointerExceptions

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

JVM automatically tells you exactly which variable was null.

Null Safety Exception Handling
Code Comparison
✕ Java 8
// Old NPE message:
// "NullPointerException"
// at MyApp.main(MyApp.java:42)
// Which variable was null?!
✓ Java 14+
// Modern NPE message:
// Cannot invoke "String.length()"
// because "user.address().city()"
// is null
// Exact variable identified!
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
🔍

Exact variable

The message names the null variable in the chain.

⚡

Faster debugging

No more guessing which of 5 chained calls was null.

🆓

Free upgrade

No code changes — just run on JDK 14+.

Old Approach
Cryptic NPE
Modern Approach
Detailed NPE
Since JDK
14
Difficulty
Beginner
JDK Support
Helpful NullPointerExceptions
Available

Widely available since JDK 14 (March 2020)

How it works

Helpful NPEs describe which expression was null and what operation failed. This is enabled by default since Java 14 — no code change needed, just upgrade the JDK.

Related Documentation
Helpful NullPointerExceptions (JEP 358) ↗
Related patterns
Errors Beginner

Null case in switch

Java 8
// Must check before switch
if (status == null) {
    return "unknown";
}
return switch (status) {
    case ACTIVE  -> "active";
    case PAUSED  -> "paused";
    default      -> "other";
};
Java 21+
return switch (status) {
    case null    -> "unknown";
    case ACTIVE  -> "active";
    case PAUSED  -> "paused";
    default      -> "other";
};
Hover to see modern ➜
JDK 21+ →
Errors Beginner

Multi-catch exception handling

Pre-Java 7
try {
    process();
} catch (IOException e) {
    log(e);
} catch (SQLException e) {
    log(e);
} catch (ParseException e) {
    log(e);
}
Java 7+
try {
    process();
} catch (IOException
    | SQLException
    | ParseException e) {
    log(e);
}
Hover to see modern ➜
JDK 7+ →
Errors Beginner

Objects.requireNonNullElse()

Java 8
String name = input != null
    ? input
    : "default";
// easy to get the order wrong
Java 9+
String name = Objects
    .requireNonNullElse(
        input, "default"
    );
Hover to see modern ➜
JDK 9+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.