首页 > 解决方案 > Java 14 中的 NullPointerException 与其前身有何不同?

问题描述

Java SE 14 引入的重要特性之一是有用的 NullPointerExceptions,它与NullPointerException. 是什么让NullPointerExceptionJava SE 14 比其前身更有用?

标签: javanullpointerexceptionjava-14

解决方案


JVMNullPointerException在代码尝试取消引用引用的程序中抛出 a null。在 Java SE 14 中,NullPointerException提供了有关程序提前终止的有用信息。从 Java SE 14 开始,JVMNullPointerException. 它通过更清晰地将动态异常与静态程序代码关联起来,极大地提高了程序的理解。

我们可以通过一个例子看出区别。

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.

很大的进步!


推荐阅读