Always Use a “default” Clause in a “switch” Statement

The following question was asked on Stack Overflow:

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.)

P.S. I recently created a nerdy privacy-respecting tool called When Will I Run Out Of Money? It's available for free if you want to check it out.

This article is © Adrian Smith.
It was originally published on 19 Feb 2013
More on: Coding | Language Design