Why is this an issue?

Good exception management is key to keeping a consistent application state in the face of errors and unexpected behaviors. However, in some cases, the information carried by the exception is not as important as the exception bubbling up itself. In such cases, developers may want to explicitly indicate that they have no use for the exception parameter. Java 22 introduces the unnamed variable pattern _ which allows developers to free the catch clause from an unnecessary exception parameter name.

How to fix it

Replace exception parameter name with unnamed variable pattern _.

Code examples

Noncompliant code example

List<String> elements = // ...
int value = 0;
try {
  var elem = elements.get(idx);
  value = Integer.parseInt(elem);
} catch (NumberFormatException nfe) { // Noncompliant
  System.err.println("Wrong number format");
} catch (IndexOutOfBoundsException ioob) {  // Noncompliant
  System.err.println("No such element");
}

Compliant solution

List<String> elements = // ...
int value = 0;
try {
  var elem = elements.get(idx);
  value = Integer.parseInt(elem);
} catch (NumberFormatException _) {
  System.err.println("Wrong number format");
} catch (IndexOutOfBoundsException _) {
  System.err.println("No such element");
}

Resources

Documentation