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 http://stackoverflow.com/questions/4649423/should-switch-statements-always-contain-a-default-clause/4649518

2 Responses to “Always use a “default” clause in a “switch” statement”

  1. Robin Salih Says:

    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.

  2. adrian Says:

    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.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

For inserting HTML or XML please remember to use &lt; instead of <