Always use a “default” clause in a “switch” statement

I was told that it’s good practice to include a default clause in all switch statements. I recently remembered this advice but can’t remember what the justification was.

Things can and do go wrong. Values will not be what you expect, and so on. To quote the old computer science motto: If it can go wrong, it will.

Not wanting to include a default clause implies you are confident that you know the set of possible values. If that’s the case, then a value which isn’t one of them indicates an error somewhere. And if that’s the case, you’d certainly want to be informed about it.

switch (myVar) {
   case 1: ......; break;
   case 2: ......; break;
   default: throw new RuntimeException("unreachable: myVar" + myVar);

There’s no reason to include more information than just the value of any variables which are known only at run-time. Anything which is visible from the source code, you don’t need to include in the text, as you’ll be looking at the source code to debug the error. (The exception stack-trace will include the line number.)

Originally from

  • Robin Salih

    I posted a comment on the original stackoverflow answer. However it occurs to me, that enums can contain values that aren’t in the list of enums. While I think this is very wrong, it does highlight the need for a default.

  • adrian

    One of the very few things I prefer about Java to C# is the way enums are handled. Enums can still be null (which is rarely what you want), but they cannot contain non-null values other than those listed, which I think is a good thing. (And you cannot cast them to/from ints.) However I would still advocate putting a “default” clause in a “switch” even for Java enums, in case more values are added to the enum in the future.