我应该抛出ArgumentNullException一个字符串是否是空白的? [英] Should I Throw ArgumentNullException if a string is blank?

查看:198
本文介绍了我应该抛出ArgumentNullException一个字符串是否是空白的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些事给定一个字符串参数的方法。字符串参数的有效值是什么,不是空的String.Empty或其他。所以,我的code看起来是这样的。

I 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
}

没有什么太令人兴奋了那里。我的问题是,是不是还好抛出一个ArgumentNullException即使字符串等的String.Empty?因为在技术上它不为空。如果你认为它不应该抛出ArgumentNullException什么异常应该抛出?

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?

推荐答案

ArgumentException的应甩了的String.Empty 情况。这表明一个问题比它被空等。为了避免的NullReferenceException 我检查空第一,那么我修剪和检查空的情况下prevent任何空白的传递。

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
}

由于.NET 4.0,你可以使用 String.IsNullOrWhiteSpace 方法来一气呵成执行这些检查。通过这样做,你放弃指定颗粒的异常类型的能力,所以我会选择在的ArgumentException 并相应地更新消息。

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.

这篇关于我应该抛出ArgumentNullException一个字符串是否是空白的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆