Helpful NullPointerExceptions

Simple classes below.

1
2
3
4
5
6
7
8
9
10
package dev.artsman.blog;

class Main {

  public static void main(String[] args) {
    var onewheel = new Onewheel();
    var brand = onewheel.tire().brand();
  }

}
1
2
3
4
5
6
7
8
9
10
package dev.artsman.blog;

class Onewheel {
  private Tire tire;

  Tire tire() {
    return this.tire;
  }

}
1
2
3
4
5
6
7
8
9
10
package dev.artsman.blog;

class Tire {
  private String brand;

  String brand() {
    return this.brand;
  }

}

Before JDK 14 the Null Pointer Exception it was like:

Exception in thread “main” java.lang.NullPointerException at dev.artsman.blog.Main.main(Main.java:7)

With JDK 14, the same exception looks like:

Exception in thread “main” java.lang.NullPointerException: Cannot invoke “dev.artsman.blog.Tire.brand()” because the return value of “dev.artsman.blog.Onewhell.tire()” is null at dev.artsman.blog.Main.main(Main.java:7)

It’s because of the JEP 358: Helpful NullPointerExceptions(https://openjdk.java.net/jeps/358).
This JEP 358 improve the usability of NullPointerExceptions generated by the JVM by describing precisely which variable was null.

Only need add this command line when run -XX:+ShowCodeDetailsInExceptionMessages and enjoy.
eof.