How does throwing an ArgumentNullException help?
Posted
by
Scott Whitlock
on Programmers
See other posts from Programmers
or by Scott Whitlock
Published on 2011-11-22T17:37:26Z
Indexed on
2011/11/22
18:14 UTC
Read the original article
Hit count: 333
Let's say I have a method:
public void DoSomething(ISomeInterface someObject)
{
if(someObject == null) throw new ArgumentNullException("someObject");
someObject.DoThisOrThat();
}
I've been trained to believe that throwing the ArgumentNullException
is "correct" but an "Object reference not set to an instance of an object" error means I have a bug.
Why?
I know that if I was caching the reference to someObject
and using it later, then it's better to check for nullity when passed in, and fail early. However, if I'm dereferencing it on the next line, why are we supposed to do the check? It's going to throw an exception one way or the other.
Edit:
It just occurred to me... does the fear of the dereferenced null come from a language like C++ that doesn't check for you (i.e. it just tries to execute some method at memory location zero + method offset)?
© Programmers or respective owner