Java 14: Helpful NullPointerException Messages
A new JVM option, -XX:+ShowCodeDetailsInExceptionMessages
, has been introduced in Java 14, in order to provide helpful NullPointerException messages showing precisely what was null when a NullPointerException
occurred. For example, consider the code below:
1 | var name = library.get( "My Book" ).getAuthor().getName(); |
Before Java 14, the JVM would only print the method, filename, and line number that caused the NPE:
1 2 | Exception in thread "main" java.lang.NullPointerException at Library.main(Library.java: 7 ) |
As you can tell, this error message is not very useful because it is impossible to determine which variable was actually null (without using a debugger). Was it the library, the book returned from the library, or the author of the book?
In Java 14, after enabling -XX:+ShowCodeDetailsInExceptionMessages
, you will get the following message:
1 2 3 | Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Author.getName()" because the return value of "Book.getAuthor()" is null at Library.main(Library.java: 7 ) |
The exception message pinpoints what was null (Book.getAuthor()
) and also displays the action that could not be performed as a result of this (Author.getName()
).
Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 14: Helpful NullPointerException Messages Opinions expressed by Java Code Geeks contributors are their own. |
What is the Iterator Design Pattern? Java Provides some built-in containers to store and access the elements. For example – the Array List or a simple Array object can do that for us. Generally, we instantiate an array object and feed into the list whatever data we need to loop over later. But what if we want to create a custom list. Say, we are creating an application for a Toy Store and it has an inventory object that contains the log of items that came in and went out and also the list of toys that needs to be… Read more »