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 AutoCloseable
s, 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.