Skip to content

[java] AvoidInstanceofChecksInCatchClause: False negative when pattern-matching instanceof #6652

@Emilyaxe

Description

@Emilyaxe

Affects PMD Version: 7.24.0

Rule: AvoidInstanceofChecksInCatchClause

Description:

AvoidInstanceofChecksInCatchClause flags traditional instanceof checks inside catch blocks but misses equivalent Java pattern-matching instanceof (Java 16+).

Code Sample demonstrating the issue:

public class Demo {
    static class ExpirationException extends RuntimeException {}
    static class Handler {
        RuntimeException handle(ExpirationException ex) { return ex; }
    }
    private final Handler h = new Handler();

    // BEFORE — pattern-matching instanceof: NO violation reported
    public void before() {
        try {
            throw new ExpirationException();
        } catch (RuntimeException ex) {
            throw ex instanceof ExpirationException e ? h.handle(e) : ex;
        }
    }

    // AFTER — traditional instanceof + cast: AvoidInstanceofChecksInCatchClause reported
    public void after() {
        try {
            throw new ExpirationException();
        } catch (RuntimeException ex) {
            throw ex instanceof ExpirationException
                    ? h.handle((ExpirationException) ex)
                    : ex;
        }
    }
}

Expected outcome: The rule reports consistently on both forms (either both flagged or both ignored), since pattern-matching instanceof is an instanceof check on the caught exception.

Running PMD through: CLI

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-negativePMD doesn't flag a problematic piece of code

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions