Missing Switch Default
ID |
java.missing_switch_default |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports classic switch statements that do not declare a default clause. Switch expressions (Java 14+) are exempt because the compiler already enforces exhaustiveness.
Rationale
A switch without default silently does nothing when the selector takes an unexpected value. Over time the set of possible values tends to grow — a new enum constant, a new status code, a new wire-level opcode — and every missing default becomes a place where behaviour is implicitly "ignore".
Explicit default has two benefits:
-
It forces the author to decide what happens for unknown values (log, throw, fall-back…).
-
It makes the intent visible to readers: "yes, we thought about it; the correct behaviour is X".
// Bad — silently no-ops for any value other than 1 or 2
switch (code) {
case 1: handleOne(); break;
case 2: handleTwo(); break;
}
Remediation
Add an explicit default. For switches over enum values where every constant is already handled, default typically throws to guard against future additions:
// Good — explicit default
switch (code) {
case 1: handleOne(); break;
case 2: handleTwo(); break;
default:
throw new IllegalArgumentException("unknown code: " + code);
}
Prefer switch expressions when possible — they require exhaustiveness and eliminate this concern at the language level:
return switch (code) {
case 1 -> handleOne();
case 2 -> handleTwo();
default -> throw new IllegalArgumentException("unknown code: " + code);
};