ChumboChappati ChumboChappati - 1 month ago 8
Java Question

What is the usage of default when the switch is for an enum?

Suppose I have an enum

Color
with 2 possible values:
RED
and
BLUE
:

public enum Color {
RED,
BLUE
}


Now suppose I have a switch statement for this enum where I have code for both possible values:

Color color = getColor(); // a method which returns a value of enum "Color"
switch (color) {
case RED:
...
break;

case BLUE:
...
break;

default:
break;
}


Since I have code block for both possible values of the enum, what is the usage of
default
in the above code?

Should I throw an exception if the code somehow reaches the
default
block like this?

Color color = getColor(); // a method which returns a value of enum "Color"
switch (color) {
case RED:
...
break;

case BLUE:
...
break;

default:
throw new IllegalArgumentException("This should not have happened");
}

Answer

It is good practice to throw an Exception as you have shown in the second example. You improve the maintainability of your code by failing fast.

In this case it would mean if you later (perhaps years later) add an enum value and it reaches the switch statement you will immediately discover the error.

If the default value were not set, the code would perhaps run through even with the new enum value and could possibly have undesired behavior.