Search code examples
javaenumsjava-5

Enums With Default Throw Clause?


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"?


Solution

  • I am not sure if I get you, but you seem to believe that the throw is part of the switch syntax in the posted code sample. That is not the case. The switch block and the throw statement are two seperate things, which just happens to be placed next to each other in this code.

    In more detail: The four case parts in the switch all contain return statements, causing any subsequent instructions in the method to be skipped. If none of the case parts matches, execution continues on the line following the switch block, which happens to be a throw.

    You could use a throw after an if in a very similar way:

    if (something) {
        return aValue;
    }
    
    throw new Exception("Nope");