Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

.net - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...