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

By Adrian Smith19 Feb 2013200 words1 mins to read

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

This article was written by Adrian Smith on 19 Feb 2013

Follow me: Facebook | Twitter | Email

More on: Coding | Language Design