66

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?

2
  • 3
    Throwing ArgumentNullException when string is "" is misleading. Commented Aug 31, 2009 at 5:46
  • I agree, alas the reason I've previously done it this way is because of the answer "Joe" gave, it is used like this in the .net framework code.
    – Kepboy
    Commented Aug 31, 2009 at 6:10

7 Answers 7

49

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.

10
  • I'm using C# 2.0, the only reference to InvalidArgumentException is in the Microsoft.SqlServer.Management.Common namespace, is what you recommend or are you suggesting that I create my own InvalidArgumentException class?
    – Kepboy
    Commented Aug 31, 2009 at 5:56
  • @Keith: you're correct, my mistake. You could write your own if you're so inclined or use the ArgumentException provided by the framework. I'll edit to reflect the proper name. Commented Aug 31, 2009 at 6:07
  • 4
    The ArgumentException constructor doesn't take a "paramName" parameter like ArgumentNullException. So 'throw new ArgumentException("paramName")' is potentially confusing, as it doesn't give any indication what's wrong with the argument. You should be providing a "message" argument something like ("someArgument may not be an empty string"). And in an international app this message would need to be localized. Hence I would only go to all this trouble if there is really a need to distinguish the null case from the empty string case.
    – Joe
    Commented Aug 31, 2009 at 6:36
  • 1
    @Joe: in this case perhaps the constructor that takes 2 string parameters would be more appropriate, the 1st being the error message and the 2nd being the parameter that caused the exception (msdn.microsoft.com/en-us/library/sxykka64.aspx). This would result in: throw new ArgumentException("Input cannot be empty", "someArgument"); Commented Aug 31, 2009 at 6:55
  • 1
    Your first statement and your code are not consistent with each other, presumably from an edit to your answer? You're throwing ArgumentNullException for the string.Empty case, and only throwing ArgumentException for non-empty whitespace strings.
    – dcstraw
    Commented Jul 26, 2012 at 16:20
5

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.

3
  • I was thinking along the lines of ArgumentOutOfRangeException but maybe that is used for array index range exceptions.
    – Kepboy
    Commented Aug 31, 2009 at 5:59
  • For array index exceptions, IndexOutOfRangeException is used. You should use ArgumentOutOfRangeException only if your method is documented to accept only a specific collection of strings (e.g.: "abc", "def", "ghi" are the only accepted inputs). Commented Aug 31, 2009 at 6:12
  • Microsoft's own documentation seems to provide conflicting advice on IndexOutOfRangeException/ArgumentOutOfRangeException topic. learn.microsoft.com/en-us/dotnet/api/… Perhaps this is where they are heading, but I tend to agree with @ronald-wildenberg on their use
    – Kepboy
    Commented Jul 17, 2020 at 5:04
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
5
  • 19
    Wouldn't it be better to derive from ArgumentException? In OOP, saying that "A or B" is an "A" doesn't seem right.
    – dcstraw
    Commented Jul 26, 2012 at 16:17
  • 1
    @dcstraw ArgumentNullException derives from ArgumentException. In this case I think it's better ArgumentNullOrEmptyException derive from ArgumentNullException.
    – Xtro
    Commented Jun 9, 2015 at 14:19
  • 1
    Also I think its name should be StringArgumentNullOrEmptyException because it only has a meaning for string arguments.
    – Xtro
    Commented Jun 9, 2015 at 14:22
  • Or... If it handles ICollection too, its name can be ArgumentNullOrEmptyException.
    – Xtro
    Commented Jun 9, 2015 at 14:23
  • ArgumentNullOrEmptyException : ArgumentException In the rare case that you want to catch ArgumentNullException, the programmer should have to treat this case differently since it might be empty. E.g. with C# 8, you may need to thrown, catch and wrap/rethrow ArgumentNullException caused by external code passing in a null where your code assumes a non-nullable input. ArgumentException from empty string would not be processed same way
    – foson
    Commented Oct 3, 2019 at 12:51
2

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)
{
   ...
}
1
  • 4
    I wouldn't look to Windows Forms for examples of the latest best practices in .NET Framework code. I was able to quickly find a counter example in File.Copy(string, string), which throws ArgumentNullException for null and ArgumentException for empty.
    – dcstraw
    Commented Jul 26, 2012 at 16:14
2

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.

2
  • There’s some discussion of why not to use the ArgumentOutOfRangeException under @ronald-wildenberg’s answer. Does that change you’re thinking at all on this? Commented Jun 10, 2020 at 3:25
  • In short, no. That answer asserts "You should use ArgumentOutOfRangeException only if your method is documented to accept only a specific collection of strings", but offers no reason as to why "range" should be defined as "specific set". A specific set is a range, as is "everything except A, B..." etc. Personally, I would also use the exception message to explain why the value is considered out of range in this specific case. But essentially, if your method does not handle a specific input value, it is "out of range" of the expected/handled values.
    – Mellevsen
    Commented Jun 11, 2020 at 1:17
0

This depends on circumstance really.

The question comes down to, is it really an error? By that I mean do you always expect a value? If you do, then probably your best bet here is creating your own Exception, perhaps like so:

class StringEmptyOrNullException : Exception
{
}

Where you can also add your own constructors and added information etc.

If it however is not an "exceptional" happening in your program, if would probably be a better idea to return null from the method and handle it from there. Just remember, Exception's are for exceptional conditions.

Hope this helps,

Kyle

3
  • 1
    If you do create your own exception, it should derive from ArgumentException rather than Exception.
    – Joe
    Commented Aug 31, 2009 at 6:28
  • Depending on context really, in this context yes. If you want to use it in other places, you make it more generic. For instance if you have a method that generates a string that shouldn't be empty, ArgumentException won't be the best choice. So, depending on the amount of use you have for it, and the context in which it is used, you will then decide on what to inherit from. Commented Aug 31, 2009 at 7:24
  • IMO those are two different situations - method generating a string and an argument passed into a method, and I would prefer to have two different exception types. It is better to be verbose than jam multiple kinds of error situations into a single exception. Commented Apr 21, 2011 at 6:22
0

Why don't use this code?

private void SomeMethod(string someArgument)
{
//chek only NULL
if(ReferenceEquals(someArgument,null))
    throw new ArgumentNullException("someArgument");

// and after trim and check
if (someArgument.Trim() == String.Empty)
    throw new ArgumentException("Input cannot be empty", "someArgument");

// do some work
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.