Helpful NullPointerExceptions

JDK 14 will have a new feature, JEP 358 – Helpful NullPointerExceptions. This feature aims to bring a better understanding to the developer about the cause of a Null Pointer Exception.

Let’s take a look at the code below:

String name = student.getName();

The JVM would produce a message like:

Exception in thread "main" java.lang.NullPointerException at Student.main (Student.java:8)

That’s not bad. Lookin g at your code you can infer that “student” is null and that’s what caused the error. But consider this scenario:

String zipCode = student.getAddress().getZipCode();

That would trigger a similar error message. But now, where’s the error coming from? It is from “student” or “getAddress”?

Starting on JDK 14, the same error message would be:

Exception in thread "main" java.lang.NullPointerException:
  Cannot read field "zipCode" because "student.getAddress" is null 
  at Student.main (Student.java:8)

Much better IMHO.

What about you? What’re your thoughts?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.