Sonar claims switch expressions on enums should have default cases (Java)

In our Azure DevOps pipeline Sonar is expecting a switch expression for an enum to have a default case and returns the following error (with the full classpath).

Unable to parse source file : 'src/..../..../Service.java'
Parse error at line 22 column 18: A switch expression should have a default case

However adding a default case would turn a compile time error if a new item is added to the enum. To a runtime error when it hits the default case. Should SonarCloud be asking switch expressions on enums to have default cases?

Here’s a super basic example of this scenario.

class Scratch {

    public static void main(String[] args) {
        Scratch s = new Scratch();
        System.out.println(s.switchExpression());
    }

    private Provider randomProvider() {
        int randomNum = (int)(Math.random() * 10);
        if (randomNum % 2 == 0) {
            return Provider.ProviderFoo;
        } else {
            return Provider.ProviderBar;
        }
    }

    private String switchExpression() {
        return switch (randomProvider()) {
            case ProviderFoo -> getFoo();
            case ProviderBar -> getBar();
            // Sonar wants a default case here
        };
    }

    private String getFoo() {
        return "foo";
    }
    private String getBar() {
        return "bar";
    }
}

// Adding a new item here would catch the error at compile time if there is no default case
public enum Provider {
    ProviderFoo,
    ProviderBar,
}

Hi @martinC ,

Thank you for your report. You are unfortunately facing a known issue with switch expressions when the analyzer is missing some semantic information, causing the parser to not realize that the switch statement is exhaustive.

We are looking into the issue - in the meantime, you can check that your sonar.java.binaries property is set appropriately.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.