Rule java:S1166 “Exception handlers should preserve the original exceptions”
states that
”When handling a caught exception, the original exception’s message and stack trace should be logged or passed forward.”
and gives a noncompliant code example
try {
/* ... */
} catch (Exception e) { // Noncompliant - exception is lost
LOGGER.info("context");
}
Now
JEP 456: Unnamed Variables & Patterns (Java 22)
explicitly suggests the use of unnamed variables in catch clauses:
String s = ...
try {
int i = Integer.parseInt(s);
... i ...
} catch (NumberFormatException _) { // Unnamed variable
System.out.println("Bad number: " + s);
}
The implementaion of the sonar rule already allows exceptions for common patterns e.g. for NumberFormatException etc.
I suggest that allowing a similar handling for all unnamed variables would be consistent with the development of Java and giving the developer the freedom how to handle exceptions at their own discression.