Improve combine catch logic, java:S2147

Please provide

  • Operating system: macOS Ventura
  • SonarLint plugin version:
  • Programming language you’re coding in: Java
  • Is connected mode used: NO

And a thorough description of the problem / question:
I’m not sure if this situation should have been covered by SONARJAVA-3578, but I’ve run into an issue where multiple catch clauses have the same code, but they cannot be collapsed, because the methods invoked on the exceptions do not inherit from the same class/interface. One comes from a library outside my control. The code looks something like the following:

try {
catch (AnException e)
  return e.getErrorCode();
catch (ASimilarExceptionOutsideMyControl e)
  return e.getErrorCode();

getErrorCode is a method defined on both exception classes above, but is not part of a shared parent class/interface. Since Java does not implement structural typing, there is no great way (of which I am aware) to collapse these two catch blocks into one. I like this code smell in general, but it would be great if the logic could recognize when/if the catch clauses can actually be collapsed.


You are right, SONARJAVA-3578 should cover it, but does not. I reopened the ticked.

Thanks for reporting!