DEV Community

loading...
Cover image for Can NullPointerException be helpful?

Can NullPointerException be helpful?

Vipin Sharma
I help professional Java developers to learn language features so they can work on the best Java projects.
Originally published at jfeatures.com Updated on ・2 min read

Have you ever received NullPointerException ?

Every Java developer has encountered NullPointerExceptions, this is most common programming error new Java Developers face.

Following is one simple programming mistake, I am trying to call method size on null list.

public class NullPointerExceptionDemo {
    public static void main(String[] args) {
        List<Integer> list = null;
        System.out.println(list.size());
    }
}
Enter fullscreen mode Exit fullscreen mode

This is output of running NullPointerExceptionDemo

Exception in thread "main" java.lang.NullPointerException
at com.vip.jdk14.NullPointerExceptionDemo.main(NullPointerExceptionDemo.java:8)

Process finished with exit code 1
Enter fullscreen mode Exit fullscreen mode

In above example it is clear list is null but several other situation it is not easy to understand root cause. See following example.

    System.out.println(objectA.getObjectB().getObjectC().getObjectD());
Enter fullscreen mode Exit fullscreen mode

Here you may get NullPointerException, when objectA or objectA.getObjectB() or objectA.getObjectB().getObjectC() any of them is null. And you get same NullPointerException message in all these cases.

Java 14 can show you root cause of NullPointerException

Now Java 14 has added language feature to show root cause of NullPointerException.
This language feature has been part of SAP commercial JVM since 2006.

Helpful NullPointerException

In Java 14 you can start passing -XX:+ShowCodeDetailsInExceptionMessages in VM arguments and it helps you to see root cause of NullPointerException.
In Java 14 option is disabled by default and in later releases this will be enabled by default.

public class HelpfulNullPointerExceptionDemo {
    public static void main(String[] args) {
        List<Integer> list = null;
        System.out.println(list.size());
    }
}
Enter fullscreen mode Exit fullscreen mode

Running this program prints following Exception message, and root cause is clearly written list is null.

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null
at com.vip.jdk14.HelpfulNullPointerExceptionDemo.main(HelpfulNullPointerExceptionDemo.java:8)

Process finished with exit code 1
Enter fullscreen mode Exit fullscreen mode

At the end

To learn the best java language features and get the best Java Jobs, download my ebook 5 steps to Best Java Jobs for Free.

Follow me on twitter @vipinbit to get daily tips like this on Java Language Features.

Discussion (0)