什么是正确的例外抛出未处理的枚举值? [英] What is the correct exception to throw for unhandled enum values?

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

问题描述

这是我的<一个又一个的情况下, href="http://stackoverflow.com/questions/13644737/what-is-the-correct-exception-to-throw-for-an-unhandled-switch-case">other关于未处理的情况下使用枚举的问题,我建议要问作为一个单独的问题。

This is another case of my other question about unhandled cases with enums which I was recommended to ask as a separate question.

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

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

enum SomeEnum
{
  One,
  Two
}

void someFunc()
{
  SomeEnum value = someOtherFunc();
  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?

推荐答案

由于是内部操作失败(产生一些无效​​),<一个href="http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx"><$c$c>InvalidOperationException是要走的路。

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

该文档简单地说:

例外,当一个方法调用对于对象的当前状态无效时引发。

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

这大概是恰当的,因为对象领先的当前状态为 someOtherFunc 的无效​​的回报价值,因此调用 someFunc 本来应该避免在首位。

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.

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

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