Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct exception to throw for unhandled enum values?

Tags:

c#

.net

exception

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?

like image 589
Sedat Kapanoglu Avatar asked Nov 30 '12 12:11

Sedat Kapanoglu


2 Answers

Personally, I add a custom exception to my project:

public class UnexpectedEnumValueException<T> : Exception {     public UnexpectedEnumValueException( T value )         : base( "Value " + value + " of enum " + typeof( T ).Name + " is not supported" )     {     } } 

Then I can use it as needed:

enum SomeEnum {   One,   Two }  void someFunc() {   SomeEnum value = someOtherFunc();   switch(value)   {    case SomeEnum.One:     ... break;    case SomeEnum.Two:     ... break;    default:       throw new UnexpectedEnumValueException<SomeEnum>(value);       } } 

That way, I can do a search for "UnexpectedEnumValueException<SomeEnum>" when I, for example, a add new value to SomeEnum and I want to find all the places that could be impacted by the change. The error message is much more clear than a generic exception.

like image 119
Pascal Avatar answered Sep 29 '22 09:09

Pascal


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.

like image 32
O. R. Mapper Avatar answered Sep 29 '22 10:09

O. R. Mapper