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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)