Enhanced NullPointerException in Java 14 (JEP 358): Enabling Detailed Exception Messages
This article explains how Java 14's JEP 358 enhances NullPointerException by providing detailed messages that pinpoint the exact null variable, how to enable this feature with a JVM flag, and the technical and security considerations involved.
Handling NullPointerException in Java has long been a pain point, especially with chained calls that can obscure the source of the null value.
Traditional NullPointerException only reports the method, file, and line number, making debugging difficult.
Java 14 introduces an enhanced NullPointerException via JEP 358, which adds detailed messages describing which variable was null.
String city = employee.getDetailInfos().getRegistryAddress().getCity();When any part of the chain is null, the JVM throws a NullPointerException.
To enable the detailed messages, start the JVM with the flag -XX:+ShowCodeDetailsInExceptionMessages .
Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "RegistryAddress.getCity()" because the return value of
"com.developlee.java14.helpfulnullpointerexceptions.HelpfulNullPointerException$DetailInfos.getRegistryAddress()" is null
at com.developlee.java14.helpfulnullpointerexceptions.HelpfulNullPointerException.main(HelpfulNullPointerException.java:10)The enhanced message shows the exact null variable, saving debugging time.
Technical details: the JVM only adds detailed messages for exceptions it throws itself, not for manually thrown ones; the computation is lazy, occurring only when the message is printed, so performance impact is minimal.
Potential security risk: detailed messages may expose local variable names if compiled with the -g debug flag.
Overall, Java 14's enhanced NullPointerException helps developers quickly locate null references, improving debugging efficiency.
Readers with Java 14 installed can try it out.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.