JDK14(Java 14)中引入一个特性:JEP 358: Helpful NullPointerExceptions,JVM在程序中代码试图取消对空引用的点抛出一个NullPointerException(NPE)。通过分析程序的字节码指令,JVM将精确地确定哪个变量是空的,并在NPE中用空的详细信息描述变量(以源代码的形式)。空的详细信息将显示在JVM的消息中,同时显示方法、文件名和行号。本主要介绍Java JDK14(Java 14) NullPointerException与之前版本区别。

NullPointerException的作用及区别

VMNullPointerException在程序试图取消引用引用的位置抛出null,JVM描述了变量(在源代码而言)与空详细消息中NullPointerException。通过更清楚地将动态异常与静态程序代码相关联,它大大提高了对程序的理解。

例如,

import java.util.ArrayList;
import java.util.List;
class Price {
double basePrice;
double tax;
public Price() {
}
public Price(double basePrice) {
this.basePrice = basePrice;
}
public Price(double basePrice, double tax) {
this.basePrice = basePrice;
this.tax = tax;
}
}
class Product {
String name;
Price price;
public Product() {
}
public Product(String name, Price price) {
this.name = name;
this.price = price;
}
}
class CartEntry {
Product product;
int quantity;
public CartEntry() {
}
public CartEntry(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
}
class Cart {
String id;
List<CartEntry> cartEntries;
public Cart() { cartEntries = new ArrayList<>(); } public Cart(String id) { this(); this.id = id; } void addToCart(CartEntry entry) { cartEntries.add(entry); } } public class Main { public static void main(String[] args) { Cart cart = new Cart("cjavapy"); cart.addToCart(new CartEntry());
//cart.cartEntries.get(0).product 是 null System.out.println(cart.cartEntries.get(0).product.price.basePrice); } }

JDK14(Java 14)之前报错信息

Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:74)

JDK14(Java 14)的报错信息

Exception in thread "main" java.lang.NullPointerException: Cannot read field "price" because "java.util.List.get(int).product" is null
    at Main.main(Main.java:74)