4 ms·
> Because this risk is always present with enums, if an exhaustive enum switch does not have a match-all clause, then the compiler will actually synthesize a de
by layer8 3y ago
> Because this risk is always present with enums, if an exhaustive enum switch does not have a match-all clause, then the compiler will actually synthesize a default clause that throws an exception. This guarantees that the switch cannot complete normally without selecting one of the clauses.
This is nice. I’ve gotten into the habit of writing such a test after each `switch` statement, for the reasons described (to not disable an exhaustiveness linter warning by presence of a default clause). I just hope they make the exception a RuntimeException (like an IllegalArgumentException) rather than an Error (like a NoSuchMethodError).
However, one disadvantage of the new pattern is that you won’t be able to do your own custom “unexpected enum value” handling any more without also disabling the exhaustiveness check (when implementing it in a match-all clause), because the synthesized check would otherwise preempt it. This is kind of a drawback. There should be an extra syntax for defining a “future case” clause.
Well, if they use a dedicated new exception type, I guess you could catch that, check that it was thrown from the right place (i.e. not thrown from some call within the explicit switch case code), and then do your custom handling. But that would be quite ugly.