正确的异常抛出一个未处理的开关情况下的参数?

正确的异常抛出一个未处理的开关情况下的参数?

问题描述:

注意:这与建议的重复项不同,因为它处理的是参数而不是值.行为和适用方案本质上是不同的.

NOTE: This is different than the proposed duplicates as this deals with an argument rather than a value. The behavior and applicable scenarios are essentially different.

假设我们有SomeEnum,并且有一个switch语句像这样处理它:

Say we have SomeEnum and have a switch statement handling it like:

enum SomeEnum
{
  One,
  Two
}

void someFunc(SomeEnum value)
{
  switch(value)
  {
     case One:
       ... break;
     case Two:
       ... break;
     default:
         throw new ??????Exception("Unhandled value: " + value.ToString());    
  }
}

如您所见,我们处理所有可能的枚举值,但仍保留默认值,以防万一添加新成员并抛出异常,我们希望确保我们知道缺少的处理.

As you see we handle all possible enum values but still keep a default throwing an exception in case a new member gets added and we want to make sure we are aware of the missing handling.

我的问题是:在这种情况下,如果您想通知给定的代码路径未处理/未实现或应该从未被访问过,那么正确的例外是什么?我们曾经使用NotImplementedException,但似乎不合适.我们的下一个候选者是InvalidOperationException,但是这个词听起来不太正确.什么是正确的,为什么?

My question is: what's the right exception in such circumstances where you want to notify that the given code path is not handled/implemented or should have never been visited? We used to use NotImplementedException but it doesn't seem to be the right fit. Our next candidate is InvalidOperationException but the term doesn't sound right. What's the right one and why?

我会抛出

I'd throw the InvalidEnumArgumentException as it will give more detailed information in this case, you are checking on an enum