Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you maintain code with InvalidEnumArgumentException?

I am curious how would you maintain your code once you throw a System.ComponentModel.InvalidEnumArgumentException.

Basically I have a switch statement like this:

switch (enumValue)
{
    case MyEnum.Value1:
        break;

    case MyEnum.Value2:
        break;

    default:
        throw new InvalidEnumArgumentException();
}

What if I decide to add more values to MyEnum in the future, for example, Value3 and Value4? That would mean I would end up throwing a misleading exception. How would I prevent this?

Should I use reflection before throwing? What exception should I throw in this case? I'm looking for suggestions.


I just discovered this exception a couple minutes ago so maybe I am looking at this in the wrong context. Is this exception thrown when a certain enum argument is not supported (in which case Value3 and Value4 would not be supported)?

like image 996
Marlon Avatar asked Jul 01 '11 09:07

Marlon


1 Answers

The problem you state depends on the context, if a method receives an enumeration as an argument it must specify what values does it support and what it does with an unknown enumeration value.

If you add more enumeration options you need to decide what to do even if you were not throwing an exception in the default case.

Be reminded that the exception is special helpful since you can pass any integer as an enumeration value.

For example:

enum Foo { A, B }

static int Bar(Foo f)
{
    switch (f)
    {
        case Foo.A:
            return 1;
        case Foo.B:
            return 2;
        default:
            throw new InvalidEnumArgumentException("f", (int)f, typeof(Foo));
    }
}

static void Main()
{
    Bar(Foo.A);
    Bar((Foo)99);
}
like image 153
João Angelo Avatar answered Nov 04 '22 21:11

João Angelo