Throwing ArgumentNullException

91,937

Solution 1

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.

Solution 2

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.

Solution 3

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?

Solution 4

No excuse not to make the check these days. C# has moved on and you can do this very neatly using a discard and a null coalescing operator:

_ = declaringType ?? throw new ArgumentNullException(nameof(declaringType));
_ = methodname ?? throw new ArgumentNullException(nameof(methodName));

Solution 5

I agree with the idea of failing fast - however it is wise to know why failing fast is practical. Consider this example:

void someMethod(SomeClass x)
{       
    x.Property.doSomething();
}

If you rely on the NullReferenceException to tell you that something was wrong, how will you know what was null? The stack trace will only give you a line number, not which reference was null. In this example x or x.Property could both have been null and without failing fast with aggressive checking beforehand, you will not know which it is.

Share:
91,937
Jason Baker
Author by

Jason Baker

I'm a developer on Google's Cloud Console.

Updated on July 05, 2022

Comments

  • Jason Baker
    Jason Baker almost 2 years

    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?

  • Jason Baker
    Jason Baker over 15 years
    Thanks! I suppose I should have spent more time reading the documentation on the constructor. :-/
  • khebbie
    khebbie over 14 years
    How about the stacktrace in the exception? It would contain the Guard method NotNull, which is only noise, and might cause confusion. Is there some way of avoiding this?
  • JamesBrownIsDead
    JamesBrownIsDead over 14 years
    Yeah, it's not a matter of preference. ArgumentNullException is correct and NullReferenceException isn't. NullReferenceException is for when a null object is <i>accessed</i>, such as a field or property of it.
  • Anastasiosyal
    Anastasiosyal over 12 years
    Agree... If only C# had the Null safe dereferncing operator then we would have something like x?.Property?.doSomething(); In that case Property would only get evaluated if x was not null etc
  • Zenexer
    Zenexer about 11 years
    @khebbie try { Guard.NotNull(...); ... } catch (Exception ex) { throw ex; } Just be sure NOT to rethrow it using throw; with no arguments, or it won't have its stack trace overwritten.
  • Sebastian
    Sebastian about 9 years
    +1 I like that "Guard" approach. The better code readability outweights the little noise in the stacktrace imo. I'd even make guard a subclass of ArgumentNullException such as MyArgumentException.ThrowIfNull(x,"x","received a null x argument!")
  • AnorZaken
    AnorZaken over 8 years
    Well it's a bit of extra work, but you can construct the stacktrace yourself and tell the stacktrace constructor to skip one frame so that the Guard.NotNull gets excluded from the trace. You of course have to inherit from your desired exception type as well and override the Exception.StackTrace property. Hmm... actually quite tempted to make a small lib for it. Well anyway you decide if it's worth it or not - it's just code-candy.
  • Jim Buck
    Jim Buck over 8 years
    @Anastasiosyal Hey, C# does have this now, almost 4 years later!
  • Anastasiosyal
    Anastasiosyal over 8 years
    Yes, at long last, it's here! Happy days :)
  • DavidRR
    DavidRR about 8 years
    If you use Code Analysis, you'll have to suppress rule CA1062: Validate arguments of public methods. That is because Code Analysis won't know that Guard.NotNull is doing the check for null.
  • Søren Ullidtz
    Søren Ullidtz over 7 years
    You don't know who might be calling your method some day in the future long after you changed jobs, or how many layers an object has passed through before reaching your method. Relying on your method not receiving null is not a viable option as it's beyond your control. Throwing a meaningful exception is within your control.
  • andrecarlucci
    andrecarlucci over 7 years
    "You don't know who might be calling your method some day in the future long after you changed jobs" <- then you have a communication problem, not a code problem. The less code, the better. For me, using argument checking brings benefit only when you need to fail fast. Otherwise, don't pass null. And btw, there will be an exception somewhere anyway.
  • Søren Ullidtz
    Søren Ullidtz over 7 years
    I would say you always need to fail fast, and make sure exceptions are meaningful. I suppose if no third parties have to use your code and you work on a small team in the same room you can be more lax about error handling. But that's rather circumstantial. In any case I think this is more of a topic for meta.
  • Marcel
    Marcel over 6 years
    This solution creates a considerable runtime overhead, so I cannot recommend it.
  • DiskJunky
    DiskJunky over 6 years
    @Marcel, "considerable" is relative. For most business/domain layer situations, it's fine - there's no noticeable lag (sub-millisecond). For a high performance piece of code? Try and avoid try/catch altogether, as it also has very high runtime overhead. It's a case of use what you need, where you need it.
  • Marcel
    Marcel over 6 years
    @DiskJunkey: I'm not talking about the exception part. This is just fine. In most implementations try/catch does not cause a significant runtime overhead unless an exception is actually thrown. The expensive part is Expression<Func<...>> which causes the runtime code to create a new expression tree before each invocation of IfArgNull, even if everything is fine and the argument is not null.
  • Marcel
    Marcel over 6 years
    +1. You might use [code contracts][1] to minimize the code overhead of ArgumentNullException: Contract.Requires<ArgumentNullException>(x != null, nameof(x)); I think this is the shortest way without significant runtime overhead. It still has the duplicate reference to x but that's the only drawback. [1]: docs.microsoft.com/en-us/dotnet/framework/debug-trace-profil‌​e/…
  • DiskJunky
    DiskJunky over 6 years
    @Marcel, you're correct that the call is comparatively expensive but given the increase in readability I think the minor performance hit is negligible in practice. Expression<Func<...>> is used liberally with LINQ for example. Performance hit, yes, but a minor one overall. In this case, readability and maintainability trumps technical performance. That's just me though :-)
  • cpsaez
    cpsaez about 6 years
    maybe im late but ive been using a similar check code from year 2014 in legacy apps (when nameof was not available) and my last tests with about 100.000 checks took 19 seconds vs 0,2 seconds with a traditionals ifs. So I had to remove it.
  • DiskJunky
    DiskJunky about 6 years
    @cpsaez, it's always a judgement call. If in a high-performance piece of code, of course avoid lambdas, anonymous delegates, etc. However, if it's a piece of code that gets hit once a second...it's not much (if at all), an issue. As with all tools; use judiciously.
  • Gabe
    Gabe over 4 years
    If you are thinking "buy why is it correct?", Martin Fowler said something that resonated with me. "Bugs are easier to find and fix, so fewer go into production." martinfowler.com/ieeeSoftware/failFast.pdf
  • Mike Marynowski
    Mike Marynowski almost 3 years
    LINQ uses Expresssions only when using IQueryable for generating SQL queries, and it (usually) does not compile and execute them, rather it just parses them. The cost of putting together a SQL query and sending it to a database is high enough that this usually doesn't have a significant impact. The cost of simply null checking a parameter v.s. using this method you've presented is crazy to use, even for non-performance sensitive code.
  • LarryBud
    LarryBud almost 3 years
    Pretty interesting syntax!
  • ryanwebjackson
    ryanwebjackson about 2 years
    That's not ideal - discards are for when you want to throw away the value, but in this case, there is no value (null). Even if you argue that it is valid to throw away null, The use of the null coalescing operator here is non-idiomatic (assigning an exception is not possible [pretend that you didn't see the exception but a method call - this is unexpected behavior]).
  • AndyWarby
    AndyWarby about 2 years
    Probably a moot point now as I would favour vivek nuna's answer for .Net 6 onwards. (That answer needs some upvotes BTW)