I was reading this post where the answerer mentioned he prefered ArgumentNullException
over NullReferenceException
.
MSDN mention that for NullReferenceException
:
The exception that is thrown when there is an attempt to dereference a null object reference.
On ArgumentNullException
they say:
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.
The answerer seems to say that you can use either.
Is there any reason or any case where I should choose one over the other?
P.S.
I know this question could be opinion based. I want fact, context and situation. I am not interested by personnal preference.
A NullReferenceException happens when you try to access a reference variable that isn't referencing any object. If a reference variable isn't referencing an object, then it'll be treated as null .
An ArgumentNullException exception is thrown when a method is invoked and at least one of the passed arguments is null but should never be null .
Find out which exception you're receiving, and either catch that specific exception, or else prevent it from occurring in the first place. You should never catch NullReferenceException.
The Null Reference Exception is not a major error, but one of the common ones and one of the basic and simple way to avoid the Null Reference Exception is to check the variable or property before moving ahead and accessing it. And a very basic way to do this is to check the variable within an if statement.
If you are explicitly throwing the exception in your code, you should choose ArgumentNullException
.
NullReferenceException
is thrown automatically by the CLR when a null reference / pointer is dereferenced:
unsafe
{
int* ptr = null; // Null pointer.
int val = *ptr; // NullReferenceException thrown.
}
This most commonly happens when method or property is called on a null reference:
string text = null;
string substring = text.Substring(0, 2); // NullReferenceException thrown.
In most cases, NullReferenceException
should not be explicitly thrown in code.
ArgumentNullException
is used to check for cases when a null reference is passed as a parameter, usually to prevent a 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.
}
The purpose of this check is to clearly let the caller know that null
was passed and null
is not allowed. Otherwise, if you simply let the NullReferenceException
be thrown, the caller would only see
Object reference not set to an instance of an object
which is not as meaningful as this (when using the check):
Value cannot be null. Parameter name: value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With