1

Is it recommended to throw an ArgumentNullException when the concerned argument is not null but one of its members is? For instance, if I have the following method:

public T Method(Blog blog)
{
    if (blog.Posts is null) 
    {
        throw new ArgumentNullException(paramName: nameof(blog.Posts));
    }
}

For this method to complete its job, it requires that blog.Posts must not be null. Was the ArgumentNullException intended to be used this way? Or would it be misleading? If so, is there another specific exception type that better suits this use case or should I just rely on the default NullReferenceException?

Amal K
  • 4,359
  • 2
  • 22
  • 44
  • 1
    I would throw `ArgumentException` for that, but I'd rather have `Blog` defined so that it can't have a null `Posts` member so that such an exception would be caught in the `Blog` constructor rather than the `Method()` call. – Matthew Watson May 18 '21 at 12:30
  • @MatthewWatson I agree. But there are cases when this isn't possible, for instance when the object comes from an external source or is deserialized; when an app uses Entity Framework, it usually does not load nested objects, even if there are multiple `Post` objects associated with a `Blog` in the database. You have to chain a call to `Include()` to ensure they are all loaded. – Amal K May 18 '21 at 12:41
  • 1
    Does this answer your question? [Use of ArgumentNullException when accessing arguments' properties](https://stackoverflow.com/questions/15099218/use-of-argumentnullexception-when-accessing-arguments-properties) – Orace May 18 '21 at 12:46

2 Answers2

2

I think it makes more sense to create your own custom exception implementing the three common constructors. You can extend ArgumentNullException.

Indrit Kello
  • 1,293
  • 8
  • 19
  • 1
    Generally, that doesn't seem very useful. For exceptions that should only ever be seen during development, creating separate exception types just makes code more complicated. – PMF May 18 '21 at 12:25
1

From the documentation:

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.

So I think ArgumentNullException is the right one, because the property is part of the passed argument. Make sure, how you already did, to provide informations, what caused the Exception.

TheTanic
  • 1,510
  • 15
  • 29
  • 1
    In addition, you can pass the name of the value that you expect to be instanciated as an agument to the exception constructor `throw new ArgumentException(nameof(blog.Posts))` – Eduard Keilholz May 18 '21 at 12:20
  • 1
    I would NOT use `nameof(blog.Posts)` because that would resolve to just `Posts` which could be quite confusing since the claimed parameter name wouldn't match the name of any actual parameter for that method. – Matthew Watson May 18 '21 at 12:33