Product: SonarQube Community (self-hosted)
sonar-java version: sonar-java 8.28.0.43176 on SonarQube Community Build 26.4.0.121862
Java source level: 21 (javac 21, source/target 17)
Rule
java:S2147 — Catches should be combined
Description
S2147 behaves inconsistently for overloaded methods vs. overloaded constructors. Two catch blocks that dispatch to different overloads based on the exception type should not be merged into a multi-catch, because doing so changes overload resolution.
Reproducer
import java.io.IOException;
public class ExceptionDispatcher {
public void run(String path) throws IOException {
// BEFORE — no S2147 raised (correct)
try {
process(path);
} catch (IOException e) {
handleException(e);
} catch (IllegalArgumentException e) {
handleException(e);
}
// AFTER — S2147 raised on the second catch (false positive)
try {
process(path);
} catch (IOException e) {
new Handler(e);
} catch (IllegalArgumentException e) {
new Handler(e);
}
}
private void process(String path) throws IOException {}
void handleException(IOException io) { System.err.println("IO: " + io); }
void handleException(IllegalArgumentException ia){ System.err.println("IA: " + ia); }
static class Handler {
Handler(IOException io) { System.err.println("IO: " + io); }
Handler(IllegalArgumentException ia){ System.err.println("IA: " + ia); }
}
}