Java 17 新特性 - Helpful NullPointerExceptions

Helpful NullPointerExceptions可以在我们遇到NPE时节省一些分析时间。如下的代码会导致一个NPE。

public static void main(String[] args) {
    Person p = new Person();
    String cityName = p.getAddress().getCity().getName();
}

在Java 11中,输出将显示NullPointerException发生的行号,但不知道哪个方法调用时产生的null,必须通过调试的方式找到。

Exception in thread "main" java.lang.NullPointerException
        at cn.pottercoding.java17.HelpfulNullPointerExceptionsDemo.main(HelpfulNullPointerExceptionsDemo.java:13)

在Java 17中,则会准确显示发生NPE的精确位置。

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "cn.pottercoding.java17.Address.getCity()" because the return value of "cn.pottercoding.java17.Person.getAddress()" is null
        at cn.pottercoding.java17.HelpfulNullPointerExceptionsDemo.main(HelpfulNullPointerExceptionsDemo.java:13)