Search code examples
c#exception

What type of Exception should I throw when an unknown value is passed into a switch statement


Edit 1

Updated to make the enum not an argument to the method...

Question

This type of problem comes up a lot with enums in switch statements. In the example code, the developer has accounted for all countries the program is currently using, but if another country is added to the Country enum, an exception should be thrown. My question is, what type of exception should be thrown?

Example Code:

enum Country
{
    UnitedStates, Mexico,
}

public string GetCallingCode(Guid countryId){
    var country = GetCountry(countryId);
    switch (country)
    {
        case Country.UnitedStates:
            return "1";
            break;
        case Country.Mexico:
            return "52";
            break;
        default:
            // What to throw here
        break;
    }
}

I've looked at

  • NotImplemented, The exception that is thrown when a requested method or operation is not implemented.
  • NotSupported There are methods that are not supported in the base class, with the expectation that these methods will be implemented in the derived classes instead. The derived class might implement only a subset of the methods from the base class, and throw NotSupportedException for the unsupported methods.
    For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see InvalidOperationException.
  • InvalidOperation is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.

My guess is either NotImplemented or Invalid Operation. Which one should I use? Does someone have a better option (I know rolling your own is always an option)


Solution

  • I would go with ArgumentException, as the agrument is invalid.

    EDIT: http://msdn.microsoft.com/en-us/library/system.argumentexception%28v=vs.71%29.aspx

    There is also InvalidEnumArgumentException, which might more accurately describe the problem, however, I have not seen anyone use it before.