Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing ArgumentNullException

Suppose I have a method that takes an object of some kind as an argument. Now say that if this method is passed a null argument, it's a fatal error and an exception should be thrown. Is it worth it for me to code something like this (keeping in mind this is a trivial example):

void someMethod(SomeClass x)
{
    if (x == null){
        throw new ArgumentNullException("someMethod received a null argument!");
    }

    x.doSomething();
}

Or is it safe for me to just rely on it throwing NullException when it calls x.doSomething()?

Secondly, suppose that someMethod is a constructor and x won't be used until another method is called. Should I throw the exception immediately or wait until x is needed and throw the exception then?

like image 851
Jason Baker Avatar asked Dec 15 '08 15:12

Jason Baker


People also ask

When should you throw an ArgumentNullException?

The ArgumentNullException is thrown when a null value is passed to a method that does not accept null values as valid input. They're provided so that application code can differentiate between exceptions caused by null arguments and exceptions caused by arguments that are not null.

How do you handle ArgumentNullException?

To prevent the error, instantiate the object. An object returned from a method call is then passed as an argument to a second method, but the value of the original returned object is null . To prevent the error, check for a return value that is null and call the second method only if the return value is not null .

Should you throw NullReferenceException?

You should never throw a NullReferenceException manually. It should only ever be thrown by the framework itself. From the NullReferenceException documentation: Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.

How do you throw an ArgumentOutOfRangeException?

An ArgumentOutOfRangeException exception is thrown when a method is invoked and at least one of the arguments passed to the method is not null and contains an invalid value that is not a member of the set of values expected for the argument.


3 Answers

I prefer the ArgumentNullException over the NullReferenceException that not checking the argument would provide. In general, my preference is to always check for nullity before trying to invoke a method on a potentially null object.

If the method is a constructor, then it would depend on a couple of different factors: is there also a public setter for the property and how likely is it that the object will actually be used. If there is a public setter, then not providing a valid instance via the constructor would be reasonable and should not result in an exception.

If there is no public setter and it is possible to use the containing object without referencing the injected object, you may want to defer the checking/exception until its use is attempted. I would think that the general case, though, would be that injected object is essential to the functioning of the instance and thus an ArgumentNull exception is perfectly reasonable since the instance can't function without it.

like image 165
tvanfosson Avatar answered Oct 04 '22 04:10

tvanfosson


I always follow the practice of fail fast. If your method is dependent on X and you understand X might be passed in null, null check it and raise the exception immediately instead of prolonging the point of failure.

2016 update:

Real world example. I strongly recommend the usage of JetBrains Annotations.

[Pure] public static object Call([NotNull] Type declaringType,                            [NotNull] string methodName,                            [CanBeNull] object instance) {     if (declaringType == null) throw new ArgumentNullException(nameof(declaringType));     if (methodName == null) throw new ArgumentNullException(nameof(methodName)); 

Guard statements have been vastly improved with C# 6 providing the nameof operator.

like image 22
Chris Marisic Avatar answered Oct 04 '22 05:10

Chris Marisic


I prefer the explicit exception, for these reasons:

  • If the method has more than one SomeClass argument it gives you the opportunity to say which one it is (everything else is available in the call stack).
  • What if you do something that may have a side effect before referencing x?
like image 44
Joel Coehoorn Avatar answered Oct 04 '22 04:10

Joel Coehoorn