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),
InvalidOperationExceptionis the way to go.The docs simply say:
which is roughly fitting, because the current state of the object lead to an invalid return value of
someOtherFunc, hence the call ofsomeFuncshould have been avoided in the first place.