Should I throw a NotImplementedException()
on default
, if I have cases for all possible enum types?
There can be at most one default statement. The default statement doesn't have to come at the end. It may appear anywhere in the body of the switch statement. A case or default label can only appear inside a switch statement.
If an exception occurs inside the switch, then it's fine. The one reasonably standard place you might throw inside a switch statement is in the default case. If reaching that case indicates invalid input, then it's reasonable to throw an exception.
The default case is always run last, no matter where it appears.
If you're looking for a value that must, by definition, correspond to the value of an enumeration, and you've received something else, that's definitely an invalid argument.
But now you have to consider the context.
Is the method private, and only accessible by members of your class library or application? If it is, it's a coding error that shouldn't EVER occur in the first place. Assert and fail.
If, on the other hand, it's a public or protected method, and can be accessed by clients consuming your library, you should definitely throw with a meaningful message (and preferably a well-known exception type).
It's important to remember that enumerations are not range-checked in the Framework. I may specify that a method requires a parameter of type Environment.SpecialFolder; but it will accept any 32-bit integer value.
So, in short, if your method is for public consumption, yes, by all means, throw. If it's not for public consumption, Assert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With