Skip to content

New Check UnusedTryResourceShouldBeUnnamed #15484

Open
@mahfouz72

Description

@mahfouz72

child of #14942
Violate the non-use of try resources. They should be unnamed.

Originally proposed to extend UnusedLocalVariableCheck in #15024 but looks like the majority is voting for a new check to achieve this behaviour.


Config

$ cat 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>

Example

public class Test {
     void test() {
         // violation below, 'Unused try resource 'a' should be unnamed'
         try (var a = lock()){
             
         } catch (Exception e) {
             
         }
         
         // ok below, declared as unnamed
         try (var _ = lock()){
             
         } catch (Exception e) {
             
         }
     }
     
     AutoCloseable lock() {
         return null;
     }
}

Expected Output

$ java -jar checkstyle-10.18.0-all.jar -c config.xml Test.java 
Starting audit...
[ERROR] D:\Test.java:4:15:Unused try resource should be unnamed [UnusedTryResourceShouldBeUnnamed]
Audit done.
Checkstyle ends with 1 errors.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions