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

enum exception java
java throw exception from enum
c# throw exception
trying to cast int to an invalid enum value will result in an exception being thrown
invalidenumargumentexception
java enum find by value
java enum valueof multiple values
c# switch default 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?


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.

What is the correct exception to throw for unhandled enum values?, Exception("Unhandled value: " + value.ToString()); } }. As you see we handle all possible enum values but still keep a default throwing an  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.


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 just 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 place that could be impacted by the change. The error message is much more clear then a generic exception.

InvalidEnumArgumentException Class (System.ComponentModel , public class InvalidEnumArgumentException : ArgumentException. C# This exception is thrown if you pass an invalid enumeration value to a method or when  What is the correct exception to throw for unhandled enum values? (6) This is another case of my other question about unhandled cases with enums which I was recommended to ask as a separate question.


Try using InvalidEnumArgumentException Class

void someFunc()
{
  SomeEnum value = someOtherFunc();
  switch(value)
  {
     case One:
       ... break;
     case Two:
       ... break;
     default:
          throw new InvalidEnumArgumentException(); 
  }
}

Pro .NET 4 Parallel Programming in C#, TaskContinuationOptions Enumeration Enumeration Value Description None the antecedent is not cancelled and does not throw an unhandled exception. What is the correct exception to throw for unhandled enum values? (6) This is another case of my other question about unhandled cases with enums which I was recommended to ask as a separate question.


I think it depends on the semantics represented by the enum.

InvalidOperationException is appropriate if it represents an object state.

NotSupportedException is appropriate if it represents an application feature that isn't supported.

NotImplementedException is appropriate for an application feature that is not currently implemented but might be in a future version.

...

Basic Error Handling with Exceptions, 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  This type of problem comes up a lot with enums in switch statements. In the example code, the developer has accounted for all countries the program is currently using, but if another country is added to the Country enum, an exception should be thrown.


The Resharper proposition for a switch case :

switch(parameter)
{
   default:
      throw new ArgumentOutOfRangeException("parameter");
}

But it could not fit your needs. If not, you can define a custom exception type regarding what is performed in this function : SomeEnumOutOfRangeException...

How to use the result type to handle errors in Swift 5?, This method is responsible for taking a string value that represents a number Throwing an exception halts further execution in the current control flow and the program reports the exception to the user as an unhandled exception. If, however, there is no appropriate catch block, the exception will fall  Using Enum.valueOf is great when you know the input is valid. However, if you pass in an invalid name, an exception will be thrown. In some cases, this is fine. Oftentimes. we would prefer to just ignore it and return null.


Foundations of C++/CLI: The Visual C++ Language for .NET 3.5, First, let me show you all the best practices of error handling in the Swift For simple scenarios you can always use optional values, to indicate that all thrown errors, so a situation of unhandled error will never occur. The result type in Swift is basically a generic enum with a .success and a .failure case. A few more considerations are worthwhile: - consider a polymorphic approach or an enum method to replace the switch statement altogether, eg: Methods inside enum in C# - if throwing is the best, as noted in other answers prefer to use a specific exception type to avoid boiler plate code, eg: InvalidEnumArgumentException


System.Text.Json: JsonStringEnumConverter ignores its , exceptions (continued) finally block, 277–279 handling structured exceptions, 416 273 throwing objects, not exceptions, 281–282 unhandled exceptions, 275 125–126 enum formatting with, 128 FlagsAttribute enumeration values as  Introduce a new exception class only when a predefined one doesn't apply. For example: Throw an InvalidOperationException exception if a property set or method call is not appropriate given the object's current state. Throw an ArgumentException exception or one of the predefined classes that derive from ArgumentException if invalid parameters are passed.


343738 – [1.5][compiler] Enum constructor that throws Exception , Deserialize<TestEnum []>(json, options); // Exception thrown here! Assert. The enum values are serialized with the naming policy successfully: [ "value_zero" Failed with unhandled exception: System.Text.Json. Unhandled Exception: System.ArgumentException: Object must be the same type as the enum. The type passed in was ‘GFG+Seasons’; the enum type was ‘GFG+Color’.