Java 14 was released for General Public usage on 17 March 2020. It brought quite a number of significant improvements for developers. Among them, Helpful NullPointerExceptions is one of the key improvements released under JEP 358. You can download Java 14 by clicking here.
Java 14 - Helpful NullPointerExceptions...!!! Click To Tweet
Check out: JAVA 13 Features with examples
JEP 358 – Helpful NullPointerExceptions
There is an improvement being made in the message thrown by NullPointerExceptions by JVM. Earlier whenever NullPointer exception used to occur, it throws a generic message but could highlight in the message that which variable threw that Null pointer exception. But, Thanks to Java, they have extended the message by adding -XX:+ShowCodeDetailsInExceptionMessages as a VM argument. Once added, It will tell that which variable is actually null.
Here is an example that will throw Null pointer exception:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class NullPointerTest { public static void main(String[] args) { String inputString = null; String result = stringConcat(inputString); System.out.println(result); } public static String stringConcat(String s) { return s.concat("abc"); } } |
Output:
Before Java 14
1 2 3 | Exception in thread "main" java.lang.NullPointerException at org.java14.examples.NullPointerTest.stringConcat(NullPointerTest.java:13) at org.java14.examples.NullPointerTest.main(NullPointerTest.java:7) |
In Java 14 (After adding -XX:+ShowCodeDetailsInExceptionMessages)
Let’s say if you are running in Eclipse, try to add ‘-XX:+ShowCodeDetailsInExceptionMessages’ as a VM argument in the Run Configurations and then execute the below code.
1 2 3 | Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.concat(String)" because "s" is null at org.java14.examples.NullPointerTest.stringConcat(NullPointerTest.java:17) at org.java14.examples.NullPointerTest.main(NullPointerTest.java:9) |
Java 14 - Helpful NullPointerExceptions...!!! Click To Tweet
Other Useful References:
- What is new in Java 13
Java 14 have some sweet features such as incubator and pattern matching for instance of. Talking about null pointer exception, a detailed message computation is only done when the JVM itself throws a NullPointerException — the computation won’t be performed if we explicitly throw the exception. Your article has simplified cover on that topic. I find it easier to grasp thanks!!
Thank you. I’m glad it helped.