UnusedCatchParameterShouldBeUnnamed

Since Checkstyle 10.18.0

Description

Ensures that catch parameters that are not used are declared as an unnamed variable.

Rationale:

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

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 catch parameters came out as the first preview in Java 21.

Examples

To configure the check:

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

Example:

class Example1 {

  void test() {

    try {
      int x = 1 / 0;
      // violation below, 'Unused catch parameter 'exception' should be unnamed'
    } catch (Exception exception) {
      System.out.println("infinity");
    }

    try {
      int x = 1 / 0;
      // ok below, 'declared as unnamed parameter'
    } catch (Exception _) {
      System.out.println("infinity");
    }

    try {
      int x = 1 / 0;
      // ok below, ''exception' is used'
    } catch (Exception exception) {
      System.out.println("Got Exception - " +  exception.getMessage());
    }

  }
}
        

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.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker