UnusedTryResourceShouldBeUnnamed

Since Checkstyle 13.5.0

Description

Ensures that try-with-resources resource variables that are not used are declared as an unnamed variable.

Rationale:

  • Improves code readability by clearly indicating which resources are unused.
  • Follows Java conventions for denoting unused variables with an underscore (_).

Only declared resources inside the try-with-resources parentheses are checked (i.e. var a = lock() or AutoCloseable a = lock()). Resources that are referenced but not declared inside the try (e.g. try (releaser) { }) are never flagged, because those resources cannot be replaced with _.

See the Java Language Specification for more information about unnamed variables.

Attention: This check should be activated only on source code that is compiled by jdk21 or higher; unnamed variables came out as a preview feature in Java 21 and became a standard part of the language in Java 22.

Examples

To configure the check:


<module name="Checker">
  <module name="TreeWalker">
    <module name="UnusedTryResourceShouldBeUnnamed">
    </module>
  </module>
</module>

Example:


public class Example1 {

  static AutoCloseable lock() {
    return () -> {};
  }

  void example() throws Exception {
    // violation below, 'Unused try resource 'a' should be unnamed'
    try (var a = lock()) {
      System.out.println("locked");
    }

    // violation below, 'Unused try resource 'res' should be unnamed'
    try (AutoCloseable res = lock()) {
      System.out.println("locked");
    }

    // ok, resource 'b' is used inside the block
    try (var b = lock()) {
      System.out.println(b);
    }

    // ok, already declared as unnamed variable
    try (var _ = lock()) {
      System.out.println("locked");
    }
  }
}

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Fully Qualified Name

com.puppycrawl.tools.checkstyle.checks.coding.UnusedTryResourceShouldBeUnnamedCheck

Use this fully qualified class name in configuration when an exact class reference is required.

Parent Module

TreeWalker