正如其他人所说的那样,尽早失败比在生产中遇到神秘问题要好得多,因为该功能没有按预期执行任何操作。如果函数返回空参数,如您的示例中所示)。
即使函数没有返回而只是抛出 a NullReferenceException
,当您知道参数为空时,也更容易解决错误。如果一个函数抛出 a NullReferenceException
,你不知道null
它是什么或是谁的错。
我想添加ArgumentNullException
一个参数是有原因的。
最好写
if(myArg == null) throw new ArgumentNullException("myArg");
而不是抛出一个ArgumentNullException
没有 a paramName
。
这样,如果您有一个带有五个参数的函数的异常,您将知道哪个参数导致了问题。如果您无法附加调试器,这一点尤其重要。(例如,在生产 Web 服务器或最终用户机器上)
如果您正在编写许多函数,这可能会产生很多开销,尤其是因为字符串没有 IntelliSense。我编写了一个代码片段来生成这些检查:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Check for null arguments</Title>
<Shortcut>tna</Shortcut>
<Description>Code snippet for throw new ArgumentNullException</Description>
<Author>SLaks</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>Parameter</ID>
<ToolTip>Paremeter to check for null</ToolTip>
<Default>value</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[if ($Parameter$ == null) throw new ArgumentNullException("$Parameter$");
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>