squid:RedundantThrowsDeclarationCheck: False-Positive when using try-with-resources

Hi,

the rule triggers an issue when using try-with-resources where a custom AutoCloseable narrows the throws-clause of the close-method. The version of SonarJava used is 5.12

Consider the following example with two different AutoCloseables, one throwing ParseException, the other one throwing IOException.

public class RemoveThrownExceptionExample {

  public void parseExceptionCloseableUser() throws ParseException {
    try (ParseExceptionCloseable closeable = new ParseExceptionCloseable()) {
      // some code
    }
  }

  public void ioExceptionCloseableUser() throws IOException {
    try (IOExceptionCloseable closeable = new IOExceptionCloseable()) {
      // some code
    }
  }

  static class ParseExceptionCloseable implements AutoCloseable {

    @Override
    public void close() throws ParseException  {
      throw new ParseException("", 0);
    }
  }

  static class IOExceptionCloseable implements AutoCloseable {

    @Override
    public void close() throws IOException {
      throw new IOException();
    }
  }
}

For the method parseExceptionCloseableUser() an issue is raised stating that the ParseException can’t be thrown by the method; removing the ‘throws’-clause, however, results in a compilation error.
For the method ioExceptionCloseableUser() no issue is raised.
Overriding a method and throwing a more concrete exception is perfectly legal and therefore the rule should not raise any issue when try-with-resources is used.

Hey @oliver ,

Thanks a lot for the feedback and the perfect reproducer. This is indeed a FP. The rule does not handle correctly the try-with-resource, and the exception which could be thrown by close() methods having different signatures.

I created the following ticket to handle it: SONARJAVA-3116

Cheers,
Michael

1 Like