Should I Throw ArgumentNullException if a string is blank?
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?
Solution 1:
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.
Solution 2:
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.
Solution 3:
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
Solution 4:
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)
{
...
}