#21613·checkstyle

False negative: UnusedTryResourceShouldBeUnnamed treats same-named identifiers in catch/finally blocks as resource usage

Author: anushkagupta200615-jpgCreated Sep 16, 2026Updated Sep 17, 2026
Labelsapproved

I have read check documentation: https://checkstyle.org/checks/coding/unusedtryresourceshouldbeunnamed.html I have downloaded the latest checkstyle from: https://checkstyle.org/cmdline.html#Download_and_Run I have executed the cli and showed it below, as cli describes the problem better than 1,000 words

bash
D:\temp\checkstyle-repro6>javac Test.java

D:\temp\checkstyle-repro6>type config.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
  "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
  "https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
  <module name="TreeWalker">
    <module name="UnusedTryResourceShouldBeUnnamed"/>
  </module>
</module>

D:\temp\checkstyle-repro6>type Test.java
import java.io.StringReader;

public class Test {
    private final StringReader reader = new StringReader("field");

    void usedInFinally() {
        try (StringReader reader = new StringReader("resource")) {
            System.out.println("body");
        } finally {
            reader.close();
        }
    }

    void usedInCatch() {
        try (StringReader reader = new StringReader("resource")) {
            System.out.println("body");
        } catch (RuntimeException ex) {
            reader.close();
        }
    }

    void notUsed() {
        try (StringReader reader = new StringReader("resource")) {
            System.out.println("body");
        }
    }
}

D:\temp\checkstyle-repro6>set RUN_LOCALE="-Duser.language=en -Duser.country=US"
D:\temp\checkstyle-repro6>java %RUN_LOCALE% -jar checkstyle-14.1.0-all.jar -c config.xml Test.java
Starting audit...
[ERROR] D:\temp\checkstyle-repro6\Test.java:23:27: Unused try resource 'reader' should be unnamed. [UnusedTryResourceShouldBeUnnamed]
Audit done.
Checkstyle ends with 1 errors.

Describe what you expect in detail.

Violations are expected on lines 7 and 15 as well:

[ERROR] D:\temp\checkstyle-repro6\Test.java:7:27: Unused try resource 'reader' should be unnamed. [UnusedTryResourceShouldBeUnnamed]
[ERROR] D:\temp\checkstyle-repro6\Test.java:15:27: Unused try resource 'reader' should be unnamed. [UnusedTryResourceShouldBeUnnamed]

According to JLS 14.20.3, the scope of a resource variable declared in a try-with-resources statement is only the resource specification and the try block. It is not in scope in catch or finally blocks.

So in usedInFinally() (line 10) and usedInCatch() (line 18), reader.close() refers to the field reader (line 4), not to the try resource. The try resources on lines 7 and 15 are never used, exactly like the one in notUsed() (line 23), which is reported.

The check currently treats any identifier with the resource name anywhere inside the whole try statement, including catch and finally blocks, as a usage of the resource.