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

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

问题描述

这是另一种情况,我的其他有关枚举的未处理案例的问题,我被建议作为一个单独的问题。



说我们有 SomeEnum 并且有一个switch语句处理它像:

 枚举SomeEnum 
{
一,
Two
}

void someFunc()
{
SomeEnum value = someOtherFunc();
开关(值)
{
案例一:
... break;
case二:
... break;
默认值:
throw new ???异常(未处理值:+ value.ToString());
}
}

如您所见,我们处理所有可能的枚举值,但仍然保留默认值抛出一个异常,以防新添加的成员被添加,我们想确保我们知道丢失的处理。



我的问题是:什么是正确的异常在这种情况下,您想要通知给定的代码路径未被处理/实现或应该从未访问过?我们曾经使用 NotImplementedException ,但似乎不合适。我们的下一个候选人是 InvalidOperationException ,但该术语听起来不正确。什么是正确的,为什么?

解决方案

由于内部操作失败(产生无效), InvalidOperationException 是要走的路。 p>

文档简单地说:


方法调用时抛出的异常对对象的当前状态无效。


这是大致适合的,因为对象的当前状态导致无效的返回值 someOtherFunc ,因此首先应避免使用 someFunc 的调用。


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

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.

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?

解决方案

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

The docs simply say:

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

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天全站免登陆