如果您明確地在您的代碼中拋出異常,應該選擇ArgumentNullException
。
NullReferenceException
當空引用/指針被解除引用被自動由CLR拋出:
unsafe
{
int* ptr = (int*)0; // Casting 0 to pointer is null reference.
int val = *ptr; // NullReferenceException thrown.
}
這最常發生在方法或屬性上調用空引用:
string s = null;
string substring = s.Substring(0, 2); // NullReferenceException thrown.
在大多數情況下,NullReferenceException
不應該顯式拋出代碼。
ArgumentNullException
用於檢查空引用作爲參數傳遞的情況,通常用於防止NullReferenceException
。
static string firstTwo(string s)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
return s.Substring(0, 2); // without the original check, this line would throw a NullReferenceException if s were null.
}
此檢查的目的是清楚地讓調用者知道null是否被傳遞,null是不允許的。否則,如果你只是讓NullReferenceException
被拋出,調用者只看到
對象引用不設置到對象
的一個實例,這是不是因爲這是有意義的(使用支票時, ):
值不能爲空。參數名:看起來像他們小號
*我應該選擇一個在另一個*你是指你應該拋出哪個,或者你應該發生什麼? – DaveShaw
非常類似的問題http://stackoverflow.com/questions/463302/argumentnullexception-or-ullullferenceexception-from-extension-method其答案與這個問題有關。 – hatchet
你也不能使用。 NRE必須保留給*實際*因解除引用而死的程序。您可以使用ArgumentNullException來*防止它們在NRE上摔倒。告訴客戶程序員「我知道你做錯了,請不要傳null」。 NRE不會發送這樣精美的消息,當它被拋出時,你不能確定它是你的錯誤還是圖書館的錯誤。 –