Skip to content

[java] NonExhaustiveSwitch fails on exhaustive switch with sealed class #5793

Closed

Description

@pkernevez

Affects PMD Version: 3.26.0

Rule: NonExhaustiveSwitch

Please provide the rule name and a link to the rule documentation:
https://pmd.github.io/pmd/pmd_rules_java_bestpractices.html#nonexhaustiveswitch

Description:
The switch is exhaustive but PMD Report an error.
Code Sample demonstrating the issue:

public class BugSealedClassTest {

    sealed interface SealedInterface permits SealedClass1, SealedClass2 {
    }

    static final class SealedClass1 implements SealedInterface {
        void method1() {
        }
    }

    static final class SealedClass2 implements SealedInterface {
        void method2() {
        }
    }

    void testSealedClass(SealedInterface sealedInterface) {
        switch (sealedInterface) {
            case SealedClass1 sealedClass1 -> sealedClass1.method1();
            case SealedClass2 sealedClass2 -> sealedClass2.method2();
            case null -> throw new IllegalStateException("Unexpected value: " + sealedInterface);
        }
    }
}

Expected outcome:
[WARNING] PMD Failure: BugSealedClassTest:19 Rule:NonExhaustiveSwitch Priority:3 Switch statements or expressions should be exhaustive, add a default case (or missing enum branches).
PMD reports a violation at line 19, but that's wrong. That's a false positive.

Running PMD through: Maven*

This bug is very close to : #5514

Activity

  1. added
    a:false-positive
    on Jun 4, 2025
  2. changed the title [-]ExhaustiveSwitchHasDefault fails on exhaustive swicth with sealed class[/-] [+][java] ExhaustiveSwitchHasDefault fails on exhaustive switch with sealed class[/+] on Jun 6, 2025
  3. changed the title [-][java] ExhaustiveSwitchHasDefault fails on exhaustive switch with sealed class[/-] [+][java] NonExhaustiveSwitch fails on exhaustive switch with sealed class[/+] on Jun 6, 2025
  4. added this to the 7.15.0 milestone on Jun 6, 2025
  5. self-assigned this
    on Jun 6, 2025
  6. adangel commented on Jun 6, 2025

    @adangel
    Member

    Thanks for reporting.
    For "NonExhaustiveSwitch" we already try to exclude switch statements, which contain pattern matching - but we didn't consider the "case null" case...
    The older issue is this one: #4813

  7. added a commit that references this issue on Jun 6, 2025
    da14e67
  8. added a commit that references this issue on Jun 20, 2025
    82aaa8f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

a:false-positive

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions