java.lang.NullPointerException

对一个 null 引用调用方法或访问字段时抛出,Java 最常见运行时异常。

现象

Exception in thread "main" java.lang.NullPointerException
    at com.demo.UserService.getEmail(UserService.java:42)
    at com.demo.Main.main(Main.java:12)

原因

解决

// 1. 早判空(防御式)
if (user != null && user.getAddress() != null) {
    String city = user.getAddress().getCity();
}

// 2. 用 Optional
Optional.ofNullable(user)
        .map(User::getAddress)
        .map(Address::getCity)
        .ifPresent(System.out::println);

// 3. 看堆栈定位到第 42 行,确认哪个变量为 null

预防

← 返回报错速查库