Skip to content

[java] UnusedLocalVariable: false-negative with try-with-resources #4516

@adangel

Description

@adangel

Affects PMD Version: 6.x

Rule: UnusedLocalVariable

Description:

If a try-with-resources defines a local variable but it is not used in the try-block, the rule should flag this variable as unused. If some weird action is happening on creation and closing (because close() is automatically executed by the try-with-resources) and the code can't be removed, then the variable should be named like unused - then it will be ignored by the rule.

Note: This is fixed already with PMD 7.0.0-rc1.
Found via #3123.

Code Sample demonstrating the issue:

import java.io.InputStream;
public class UnusedUsedLocalVar {
    public boolean run() {
        boolean canRead = false;
        try(InputStream resource = open()) { // violation expected
            canRead = true;
        } catch (Throwable ignore) {}
        return canRead;
    }
    private InputStream open() { return null; }
}

Expected outcome:

PMD should report a violation at line 5, but doesn't. This is a false-negative.

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