Do you know Java: Helpful NullPointerExceptions


Java 14 has brought a helpful feature with that we can get information about the source of the raised NullPointerException

NullPointerException is not very friendly and can occur anywhere. All the placed where we don’t want it to be. In this post I will show you how to track down its source.

The following source code is given:

String value = null;
System.out.println(value.length());

Pre Java 14 Era

The good old error message is the following:

$ java NPEDemo                                        
Exception in thread "main" java.lang.NullPointerException
	at NPEDemo.main(NPEDemo.java:5)

Java 14 Era

A new command-line option was introduced, called -XX:{+|-}ShowCodeDetailsInExceptionMessages. That is false by default, so detailed message won’t be shown.

$ java -XX:+ShowCodeDetailsInExceptionMessages NPEDemo
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>" is null
	at NPEDemo.main(NPEDemo.java:5)

You can find more here: JEP 358: Helpful NullPointerExceptions

What a good feature has been brought by Java 14!

Code can be found: https://github.com/torokmark/do-you-know-java