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)