Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
adangel opened this issue Apr 28, 2023 · 0 comments · Fixed by #4501
Closed

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

adangel opened this issue Apr 28, 2023 · 0 comments · Fixed by #4501
Labels
a:false-negative PMD doesn't flag a problematic piece of code
Milestone

Comments

@adangel
Copy link
Member

adangel commented Apr 28, 2023

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.

@adangel adangel added the a:false-negative PMD doesn't flag a problematic piece of code label Apr 28, 2023
@adangel adangel added this to the 7.0.0 milestone Apr 28, 2023
@adangel adangel changed the title [java] UnusedLocalVariable false-negative with unused try-with-resources [java] UnusedLocalVariable: false-negative with try-with-resources Apr 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
a:false-negative PMD doesn't flag a problematic piece of code
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant