Today we wanted to write some code in java that performs some or the other action depending on a condition. At the same time if some action fails we wanted to fall back to the other action.
We've written it like this:
switch(boolean_expression) { case true: { try { // Some actions. break; } catch(Exception e) { // Fall back to false route. } } case false: { // Other actions. break; } }
The fun part is that it's not valid java code.
Why?
The answer can be found in spec: 14.11. The switch Statement
switch
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (ยง8.9), or a compile-time error occurs.
char
byte
short
int
Character
Byte
Short
Integer
String
But why?
Who knows...
Sure there are workarounds, even with switch, but it just not justified restriction...