So 10000 is not a valid enum value
That may be true, but not because it's not equal to X1
or X2
. An enum doesn't have to hold one of the named enumerators. It can hold any value in its integer range.
Now, the actual range of MYENUM
is up to the compiler, as long as the integral underlying type it picks can represent both X1
and X2
. So, it could be a int8_t
, for example, which cannot hold 10000.
(In practice, it's probably an int
here.)
How would you personally find a solution to this? Would you encase the map access in a try block and catch the exception?
Yes, if you like.
There are many approaches to error handling for functions like this, whether they involve enums or not. You can throw an exception (the .at()
call will already do this for you, but you could catch it and throw an exception of your own type if you liked).
You could populate an error code, return a placeholder value, return a std::optional
… or just ignore it, and document that the user of your function must pass a named member of the enum
, or fall foul of a sort of "undefined behaviour" (possibly choosing to have the function act as if X1
were passed in that case, so that it has something to do at least).
All the usual options.
What if I have many functions which access container information with user input enum values - would you then put try catch in all of them too?
That is indeed a possible consideration to bear in mind when choosing your input argument error handling methodology.