Should I Throw ArgumentNullException if a string is blank?

Viewed 19416

I'm working on a method that does something given a string parameter. A valid value for the string parameter is anything other than null or string.Empty. So my code looks like this.

private void SomeMethod(string someArgument)
{
    if(string.IsNullOrEmpty(someArgument))
        throw new ArgumentNullException("someArgument");

    // do some work
}

Nothing too exciting there. My question is, is it okay to throw an ArgumentNullException even if the string is equal to string.Empty? Because technically it isn't null. If you believe it should not throw ArgumentNullException, what exception should be thrown?

7 Answers

Old question, but since Google ranks it highly, here's another (better!) option for future readers: ArgumentOutOfRangeException.

ArgumentException is the base class for both ArgumentNullException and ArgumentOutOfRangeException, amongst others. That means it's more generic and less informative to developers who are handling the exception. In other words, whilst all ArgumentNullExceptions and ArgumentOutOfRangeExceptions are also ArgumentExceptions, the reverse is not true.

ArgumentOutOfRangeException is a more specific exception which says "the value you provided was not in the range of values I expected", which is exactly what you're trying to tell other developers. It's the best standard exception type if you won't accept an empty string.

Alternatively, create your own exception type derived from ArgumentNullException, if it's really important to distinguish between values.

When handling your exception, other developers who don't need to distinguish why the value they supplied was wrong can just catch ArgumentException and get them all at once.

Related