[Java:S2147] Sonar suggests to combine catch clauses when it is not possible

Versions:

  • SonarCloud
  • Java compiler source and target: 14

Code sample:

    class SneakingPastTeeFilterException extends RuntimeException {
        private final Exception wrapped;

        public SneakingPastTeeFilterException(IOException e) {
            this.wrapped = e;
        }

        public SneakingPastTeeFilterException(ServletException e) {
            this.wrapped = e;
        }

        void unwrap() throws IOException, ServletException {
            if (wrapped instanceof IOException) {
                throw (IOException) wrapped;
            } else {
                throw (ServletException) wrapped;
            }
        }

        private static class WrappingFilter implements Filter {
            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
                try {
                    chain.doFilter(request, response);
                } catch (IOException e) {
                    throw new SneakingPastTeeFilterException(e);
                } catch (ServletException e) {
// S2147 reported here: "Combine this catch with the one at line 63, which has the same body."
//   even when a different constructor is called
                    throw new SneakingPastTeeFilterException(e);
                }
            }
        }
    }

Hello @grimsa,

Thanks for the clear reproducer, and the interesting problem.

Indeed, this is a wrong behavior of the rule, ticket created: SONARJAVA-3578.

Best,
Quentin

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.