小编LiJ*_*ing的帖子

为什么显式抛出NullPointerException而不是让它自然发生?

在阅读JDK源代码时,我发现作者通常会检查参数是否为null,然后手动抛出新的NullPointerException().他们为什么这样做?我认为没有必要这样做,因为它会在调用任何方法时抛出新的NullPointerException().(这里是HashMap的一些源代码,例如:)

public V computeIfPresent(K key,
                          BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
    if (remappingFunction == null)
        throw new NullPointerException();
    Node<K,V> e; V oldValue;
    int hash = hash(key);
    if ((e = getNode(hash, key)) != null &&
        (oldValue = e.value) != null) {
        V v = remappingFunction.apply(key, oldValue);
        if (v != null) {
            e.value = v;
            afterNodeAccess(e);
            return v;
        }
        else
            removeNode(hash, key, null, false, true);
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

java nullpointerexception

182
推荐指数
8
解决办法
1万
查看次数

标签 统计

java ×1

nullpointerexception ×1