I noticed the following in the Java Language spec in the section on enumerations here: link
switch(this) {
case PLUS: return x + y;
case MINUS: return x - y;
case TIMES: return x * y;
case DIVIDE: return x / y;
}
throw new AssertionError("Unknown op: " + this);
However, looking at the switch statement definition section, I didn’t notice this particular syntax (the associated throw statement) anywhere.
Can I use this sort of “default case is throw an exception” syntactic sugar outside of enum definitions? Does it have any special name? Is this considered a good/bad practice for short-cutting this behavior of “anything not in the list throws an exception”?
I am not sure if I get you, but you seem to believe that the
throwis part of theswitchsyntax in the posted code sample. That is not the case. Theswitchblock and thethrowstatement are two seperate things, which just happens to be placed next to each other in this code.In more detail: The four
caseparts in theswitchall containreturnstatements, causing any subsequent instructions in the method to be skipped. If none of thecaseparts matches, execution continues on the line following theswitchblock, which happens to be athrow.You could use a
throwafter anifin a very similar way: