Exceptions: a helpful NullPointerException message names the null variable

Modern JVMs generate a detailed message for an unhandled null dereference, naming the exact field and method call involved, which turns a bare NullPointerException into an actionable clue instead of a mystery.

Code
class Order {
    String customerName;
}
try {
    Order order = new Order();
    System.out.println(order.customerName.length());
} catch (NullPointerException e) {
    System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
Output
NullPointerException: Cannot invoke "String.length()" because "<local1>.customerName" is null
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms