java - Java 14 中的 NullPointerException 与其前身有何不同?
问题描述
Java SE 14 引入的重要特性之一是有用的 NullPointerExceptions,它与NullPointerException
. 是什么让NullPointerException
Java SE 14 比其前身更有用?
解决方案
JVMNullPointerException
在代码尝试取消引用引用的程序中抛出 a 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
.
很大的进步!
推荐阅读
- r - 在 dockerization 期间安装了错误的 R 版本
- architecture - 如何仅在事件驱动架构中接收到两个或多个事件后才触发动作?
- c# - 如何确定客户端是否可以使用 IdentityServer4 调用 api 端点
- javascript - 如何在本地主机上开发时使 Progressive Web App 的启动画面图标可用
- algorithm - 查找关节点组
- date - #docusignAPI 获取数据发送时间
- algorithm - 通过最大流量约束在未加权图中找到最短路径
- angular6 - Angular 6 [ngValue] 未定义
- javascript - 如何使用 JQuery 在空文档中附加 HTML 标签?
- python - 如何修复烧瓶应用程序中的 url_prefix?