c# - NullReferenceException 与 ArgumentNullException

标签 c# exception nullreferenceexception

我正在阅读 this post回答者提到他更喜欢 ArgumentNullException 而不是 NullReferenceException

MSDN提到 NullReferenceException:

The exception that is thrown when there is an attempt to dereference a null object reference.

关于 ArgumentNullException they说:

The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.

回答者似乎说你可以使用任何一个。

有什么理由或任何情况我应该选择一个而不是另一个吗?

附言

我知道这个问题可能是基于意见的。 我想要事实、背景和情况。我对个人偏好不感兴趣。

最佳答案

如果您在代码中明确抛出异常,则应选择 ArgumentNullException

NullReferenceException 在取消引用空引用/指针时由 CLR 自动抛出:

unsafe
{
    int* ptr = null; // Null pointer.
    int val = *ptr; // NullReferenceException thrown.
}

这最常发生在对空引用调用方法或属性时:

string text = null;
string substring = text.Substring(0, 2); // NullReferenceException thrown.

在大多数情况下,不应在代码中显式抛出 NullReferenceException

ArgumentNullException 用于检查空引用作为参数传递的情况,通常是为了防止 NullReferenceException

static string FirstTwo(string value)
{
    if (value == null)
    {
        throw new ArgumentNullException(nameof(value));
    }
    return value.Substring(0, 2); // without the original check, this line would throw a NullReferenceException if value were null.
}

这个检查的目的是为了让调用者清楚的知道null是通过的,null是不允许的。否则,如果您只是让 NullReferenceException 被抛出,调用者只会看到

Object reference not set to an instance of an object

这不像这样有意义(使用支票时):

Value cannot be null. Parameter name: value

关于c# - NullReferenceException 与 ArgumentNullException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39520241/

相关文章:

c# - 如何在维护到目前为止生成的堆栈跟踪的同时重新抛出内部异常?

c# - 如何将空引用分析的结果写入日志文件

c# - 这段 Winform C# 代码有什么问题?它在 Windows 中运行良好,但在 mono(Linux) 中,将抛出 NullReferenceException

c# - DateTime.Parse 在特定文化中总是抛出异常

c# - Azure Function 在 bin 文件夹中创建文件夹?

C# --> 转到定义 ==> VB.NET

c# - 我认为我误解了 Unity3d 的层次结构系统

.net - 用于异常处理的开源服务器应用程序?

vb.net - Task.Run - 处理异常

c# - 数组比较(T)委托(delegate) NullReferenceException