Skip to content

[java] UseTryWithResources false positive when AutoCloseable helper used #2650

@amarkevich

Description

@amarkevich

Affects PMD Version:

maven-pmd-plugin 3.13.0 (pmd 6.21.0)

Rule: UseTryWithResources

Description:

PMD Failure: UseTryWithResources when resource is not AutoCloseable and closed via external class which implement AutoCloseable

Code Sample demonstrating the issue:

public class PMDUseTryWithResources {

    static class ResourceCloser implements AutoCloseable {
        public static void close(NotAutoCloseable notAutoCloseable) {
            notAutoCloseable.close();
        }

        @Override
        public void close() throws Exception {
            // nothing
        }
    }

    interface NotAutoCloseable {
        void close();
    }

    public void useTryWithResources() {
        NotAutoCloseable notAutoCloseable = null;
        try {
            notAutoCloseable = new NotAutoCloseable() {
                @Override
                public void close() {
                }
            };
        } finally {
            if (notAutoCloseable != null) {
                ResourceCloser.close(notAutoCloseable);
            }
        }
    }
}

Steps to reproduce:

  1. mvn install

Running PMD through: Maven

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    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