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...!!! Share on X

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:

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

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.

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...!!! Share on X

Other Useful References:

    • What is new in Java 13

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts