Java SE 14引入的重要功能之一是 Helpful NullPointerExceptions ,它与NullPointerException
的可用性有关。是什么使Java SE 14中的NullPointerException
比其前身更有用?
最佳答案
JVM在程序试图取消引用NullPointerException
引用的位置上抛出null
。在Java SE 14中,NullPointerException
提供了有关程序过早终止的有用信息。从Java SE 14开始,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("XYZ123");
cart.addToCart(new CartEntry());
System.out.println(cart.cartEntries.get(0).product.price.basePrice);
}
}
Java SE 14之前的输出:Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:74)
该消息使程序员对NullPointerException
的来源一无所知。从Java SE 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)
Java SE 14中的NullPointerException
还告诉哪个引用是null
。很大的进步!
关于java - Java 14中的NullPointerException与之前的版本有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65659746/