Missing enum case in switch¶
ID: java/missing-case-in-switchKind: problemSecurity severity: Severity: warningPrecision: mediumTags: - quality - reliability - correctness - external/cwe/cwe-478Query suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
Aswitch statement that is based on a variable with anenum type should either have a default case or handle all possible constants of thatenum type. Handling all but one or twoenum constants is usually a coding mistake.
Recommendation¶
If there are only a handful of missing cases, add them to the end of theswitch statement. If there are many cases that do not need to be handled individually, add a default case to handle them.
If there are someenum constants that should never occur in this particular part of the code, then program defensively by adding cases for those constants and explicitly throwing an exception (rather than just having no cases for those constants).
Example¶
In the following example, the case for ‘YES’ is missing. Therefore, ifanswer is ‘YES’, an exception is thrown at run time. To fix this, a case for ‘YES’ should be added.
enumAnswer{YES,NO,MAYBE}classOptimist{Answerinterpret(Answeranswer){switch(answer){caseMAYBE:returnAnswer.YES;caseNO:returnAnswer.MAYBE;// Missing case for 'YES'}thrownewRuntimeException("uncaught case: "+answer);}}
References¶
Help - Eclipse Platform:Java Compiler Errors/Warnings Preferences.
Java Language Specification:8.9 Enum Types,14.11 The switch Statement.
Common Weakness Enumeration:CWE-478.