java14新特性-改进NullPointerExceptions提示信息

在 Java 14 中引入的 Helpful NullPointerExceptions 特性,对开发者处理空指针异常提供了极大的帮助。这个功能改进了 NullPointerException 的错误信息,使得调试和排查空指针问题变得更加容易和高效

NullPointerExceptions旧信息

传统上,当程序遇到空指针异常时,错误信息通常非常简单,只告诉我们发生了空指针异常,但不会指明具体哪个变量为空

Exception in thread "main" java.lang.NullPointerException

Helpful NullPointerExceptions的改进

Java 14 引入了 Helpful NullPointerExceptions,它提供了更详细的错误信息,指明了哪个变量为空,从而大大简化了调试过程

  1. 更详细的错误信息

在 Java 14 中,当发生空指针异常时,错误信息将会指出具体是哪个变量或表达式导致了异常

Exception in thread "main" java.lang.NullPointerException: Cannot read field "name" because "person" is null
  1. 对复杂表达式的支持

Helpful NullPointerExceptions 不仅对简单的变量访问有帮助,对于复杂的链式调用和表达式也能够提供详细的错误信息

public class Main {
public static void main(String[] args) {
User user = new User();
String streetName = user.getContactInfo().getAddress().getStreet().getName();
}
}

class User {
private ContactInfo contactInfo = null;
public ContactInfo getContactInfo() { return contactInfo; }
}

class ContactInfo {
private Address address;
public Address getAddress() { return address; }
}

class Address {
private Street street;
public Street getStreet() { return street; }
}

class Street {
private String name;
public String getName() { return name; }
}

运行结果:

Exception in thread "main" java.lang.NullPointerException: 
Cannot invoke "Address.getStreet()" because the return value of "ContactInfo.getAddress()" is null

启用方法

-XX:+ShowCodeDetailsInExceptionMessages

弊端

  1. 性能影响:因为要存储额外的信息,对 stack trace会有性能上面的压力。
  2. 安全影响:从上面的例子我们可以看到异常信息中包含了非常充分的代码信息内容。如果对一些机密应用,完全可以通过异常信息来推断代码逻辑。从而对安全性造成影响。
  3. 兼容性:最后是兼容性,之前的JVM可没有存储这些额外的NPE信息,所以可能会有兼容性的问题。