Alex Rivera | Logout

What Exception Type to throw for strings

Asked 2010-01-19T19:06:57.653
11

If I've got the following, really for any string where you check IsNullOrEmpty and it turns up empty, what kind of exception type should one throw, and it's not a argument to a method?

I always have a hard time picking exception types because there are so damn many of them. And this is just grabbing a value from the web.config and checking if SandboxSoapApiUsername returned empty.

if(string.IsNullOrEmpty(ConfigUtility.SandboxSoapApiUsername))
        throw new WTF do I throw here??? ahhh

It probably depends on the use/context right? Well I will use the string returned to set a class private field. So I need to check if it's empty string early in the process rather than later (rather than rely on other code to check the property related to the private field I will set ConfigUtility.SandboxSoapApiUsername to).

Since the properties in this class that I'm setting each ConfigUtility.MEthodName to is going to be used in a SOAP request I thought maybe UriFormatException would be appropriate here even though this is not the Uri?

Edit
Report

3 Answers

12

Methods in the .NET Framework usually distinguish between null and an invalid value passed in for an argument. I think you should throw an Argument​Null​Exception if the value is null and an Argument​Exception if it's invalid.

if (arg == null)
    throw new ArgumentNullException("arg", "argcannot be null");
if (arg == string.Empty)
    throw new ArgumentException("arg cannot be an empty string", "arg");

If the value is not an argument, but, for example, loaded during initialization, I think a Invalid​Operation​Exception would be appropriate:

if (string.IsNullOrEmpty(ConfigUtility.SandboxSoapApiUsername))
    throw new InvalidOperationException("Cannot initialize because " +
                                        "SandboxSoapApiUsername not configured");
answered 2010-01-19T19:11:27.847
4

you need an InvalidConfiguration exception - define one

 throw new InvalidConfigurationException("Must supply user name")
answered 2010-01-19T19:11:58.323
0

Since it seems something wasn't configured correctly, I'd suggest System.Configuration.ConfigurationErrorsException.

Note: don't use System.Configuration.ConfigurationException. It's an older version and has been deprecated.

Note 2: Though I'm 90% sure we're dealing with a missing configuration value, if it's an method parameter that's missing, throw an ArgumentException or ArgumentOutOfRangeException.

answered 2010-01-19T19:12:32.273

Your Answer