Should I Throw ArgumentNullException if a string is blank?

Taking all the things into account that have been said (Joe / Ahmad Mageed), I would create an exception for that case then.

class ArgumentNullOrEmptyException : ArgumentNullException

ArgumentNullException is sometimes used in the .NET Framework for the String.IsNullOrEmpty case - an example is System.Windows.Forms.Clipboard.SetText.

So I think it's reasonable to do the same in your code, unless there is some real value in distinguishing the two cases.

Note that this and other exceptions derived from ArgumentException generally indicate a programming error, and therefore need to provide information needed to help a developer diagnose the problem. Personally I think it's unlikely that a developer would find it confusing if you use ArgumentNullException for an empty string argument, especially if you document this behavior as in the example below.

/// <summary>
/// ... description of method ...
/// </summary>
/// <param name="someArgument">... description ...</param>
/// <exception cref="ArgumentNullException">someArgument is a null reference or Empty.</exception>
public void SomeMethod(string someArgument)
{
   ...
}

You should throw an ArgumentException if an empty string is not an accepted input for your method. It may be very confusing to clients if you throw an ArgumentNullException while they didn't provide a null argument.

It is simply another use case. You may also have methods that do not accept null input values but that do accept empty strings. It's important to be consistent across your entire application.


ArgumentException should be thrown for the String.Empty case. This would indicate an issue other than it being null. To avoid a NullReferenceException I check for null first, then I trim and check for the empty case to prevent any whitespace from passing.

private void SomeMethod(string someArgument)
{
    if(someArgument == null)
        throw new ArgumentNullException("someArgument");

    if (someArgument.Trim() == String.Empty)
        throw new ArgumentException("Input cannot be empty", "someArgument");

    // do some work
}

As of .NET 4.0 you can use the String.IsNullOrWhiteSpace method to perform these checks in one go. By doing so you forgo the ability to specify a granular exception type, so I would opt for the ArgumentException and update the message accordingly.

Tags:

.Net