What is the correct exception to throw for unhandled enum values?

Personally, I add a custom exception to my project:

public class UnexpectedEnumValueException<T> : Exception
{
    public UnexpectedEnumValueException( T value )
        : base( "Value " + value + " of enum " + typeof( T ).Name + " is not supported" )
    {
    }
}

Then I can use it as needed:

enum SomeEnum
{
  One,
  Two
}

void someFunc()
{
  SomeEnum value = someOtherFunc();
  switch(value)
  {
   case SomeEnum.One:
    ... break;
   case SomeEnum.Two:
    ... break;
   default:
      throw new UnexpectedEnumValueException<SomeEnum>(value);    
  }
}

That way, I can do a search for "UnexpectedEnumValueException<SomeEnum>" when I, for example, a add new value to SomeEnum and I want to find all the places that could be impacted by the change. The error message is much more clear than a generic exception.


Try using InvalidEnumArgumentException Class

void someFunc()
{
  SomeEnum value = someOtherFunc();
  switch(value)
  {
     case One:
       ... break;
     case Two:
       ... break;
     default:
          throw new InvalidEnumArgumentException(); 
  }
}

As it is an internal operation that fails (produces something invalid), InvalidOperationException is the way to go.

The docs simply say:

The exception that is thrown when a method call is invalid for the object's current state.

which is roughly fitting, because the current state of the object lead to an invalid return value of someOtherFunc, hence the call of someFunc should have been avoided in the first place.

Tags:

C#

.Net

Exception