In Java 14, along with the -XX:+ShowCodeDetailsInExceptionMessages
feature, Helpful NullPointerExceptions were introduced. This feature provides detailed and precise messages when a NullPointerException
(NPE) occurs. It is available starting from Java 14 as a preview feature and was enabled by default (no longer requiring the JVM flag) starting with Java 16. This behavior continues in Java 17.
These enhancements tell you exactly which object reference was null
, making debugging easier compared to the default NPE messages.
Steps to Use Helpful NullPointerExceptions in Java 17
- Ensure Java 17 is Installed
- Verify that the installed JDK version is Java 17 or newer. Use:
java -version
- By Default, It’s Enabled
- Starting from Java 16, Helpful NullPointerExceptions are enabled by default, so no additional JVM flag or setup is required.
- Run Your Application
- If your code throws a
NullPointerException
, the detailed message will be generated.
- If your code throws a
- How It Works
- When a
NullPointerException
is thrown, the JVM will now include details in the exception’s message about thenull
reference that caused the problem.
- When a
Example
Code Example
package org.kodejava.basic;
public class NullPointerDemo {
public static void main(String[] args) {
String str = null;
System.out.println(str.toLowerCase()); // Will throw a NullPointerException
}
}
Output
Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "String.toLowerCase()" because "str" is null
If you use field/method chaining, the message will identify exactly which part caused the NPE.
Example with Field Access
class Person {
Address address;
}
class Address {
String city;
}
public class HelpfulNPEExample {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.address.city); // Accessing null property
}
}
Detailed Output
Exception in thread "main" java.lang.NullPointerException:
Cannot read field "city" because "person.address" is null
Enabling or Disabling (Optional)
Helpful NullPointerExceptions can be disabled using the following JVM argument:
-XX:-ShowCodeDetailsInExceptionMessages
To enable explicitly (though it’s enabled by default in Java 17+):
-XX:+ShowCodeDetailsInExceptionMessages
Add this argument when running your application:
java -XX:+ShowCodeDetailsInExceptionMessages YourMainClass
Benefits of Helpful NullPointerExceptions
- Faster Debugging: You no longer need to search manually for which variable or reference is
null
. - Enhanced Error Information: Pinpoints the exact null reference, which is especially useful in complex codebases.
- Productivity Increase: Saves time during troubleshooting and debugging.
Java 17 users benefit from this feature out-of-the-box, making it a significant enhancement for clean and error-free development.