为什么显式抛出 NullPointerException 而不是让它自然发生? [英] Why explicitly throw a NullPointerException rather than letting it happen naturally?

查看:18
本文介绍了为什么显式抛出 NullPointerException 而不是让它自然发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When reading JDK source code, I find it common that the author will check the parameters if they are null and then throw new NullPointerException() manually. Why do they do it? I think there's no need to do so since it will throw new NullPointerException() when it calls any method. (Here is some source code of HashMap, for instance :)

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;
}

推荐答案

有很多原因浮现在脑海中,其中几个是密切相关的:

There are a number of reasons that come to mind, several being closely related:

快速失败:如果要失败,最好尽早失败.这允许更接近问题的源头发现问题,使它们更容易识别和恢复.它还避免了将 CPU 周期浪费在必然会失败的代码上.

Fail-fast: If it's going to fail, best to fail sooner rather than later. This allows problems to be caught closer to their source, making them easier to identify and recover from. It also avoids wasting CPU cycles on code that's bound to fail.

意图: 抛出异常明确地让维护者清楚地表明错误是故意存在的,并且作者知道后果.

Intent: Throwing the exception explicitly makes it clear to maintainers that the error is there purposely and the author was aware of the consequences.

一致性:如果允许错误自然发生,它可能不会在所有情况下都发生.例如,如果没有找到映射,则永远不会使用 remappingFunction 并且不会抛出异常.提前验证输入允许更确定的行为和更清晰的文档.

Consistency: If the error were allowed to happen naturally, it might not occur in every scenario. If no mapping is found, for example, remappingFunction would never be used and the exception wouldn't be thrown. Validating input in advance allows for more deterministic behavior and clearer documentation.

稳定性:代码会随着时间的推移而发展.遇到异常的代码自然可能会在稍微重构后停止,或者在不同情况下会停止.明确地抛出它可以减少无意中改变行为的可能性.

Stability: Code evolves over time. Code that encounters an exception naturally might, after a bit of refactoring, cease to do so, or do so under different circumstances. Throwing it explicitly makes it less likely for behavior to change inadvertently.

这篇关于为什么显式抛出 NullPointerException 而不是让它自然发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆