什么是正确的例外抛出的未处理的开关呢? [英] What is the correct exception to throw for an unhandled switch case?

查看:137
本文介绍了什么是正确的例外抛出的未处理的开关呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  <一href="http://stackoverflow.com/questions/3349540/c-throwing-exceptions-in-switch-statements-when-no-specified-case-can-be-handl">C#:扔在switch语句异常时,没有指定的情况下,可以处理

假设我们有 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.

我的问题是:什么是正确的异常在这种情况下,你要通知给定的code路径没有被处理/执行或应该从未访问过?我们以前使用 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?

推荐答案

InvalidArgumentException 看起来最正确的,我在此情况下(虽然没有在BCL中定义)。

InvalidArgumentException looks the most correct to me in this instance (though is not defined in the BCL).

有一个专门的例外枚举参数 - <一个href="http://msdn.microsoft.com/en-us/library/system.componentmodel.invalidenumargumentexception.aspx"相对=nofollow> InvalidEnumArgumentException :

There is a specialized exception for enum arguments - InvalidEnumArgumentException:

使用无效的参数是统计员时引发的异常。

The exception thrown when using invalid arguments that are enumerators.

另一种方法是 ArgumentOutOfRangeException

例外,当一个参数的值超出由调用方法定义的值的允许范围时引发。

The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.

有关使用这些的逻辑是,在参数传递()是无效的,只要 someFunc 关注。

The logic for using these is that the passed in argument (value) is not valid as far as someFunc is concerned.

这篇关于什么是正确的例外抛出的未处理的开关呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆