rewrite-static-analysis icon indicating copy to clipboard operation
rewrite-static-analysis copied to clipboard

`Remove catch for a checked exception if the try block does not throw that exception` removes exception thrown by close in try-with-resources on `XsltTransformationVisitor`

Open timtebeek opened this issue 5 months ago • 1 comments

Problem

Exception is removed when it is thrown by a try-with-resources close method in our very own code base: https://github.com/openrewrite/rewrite/blob/0fb707186f69d4cd4518388f7180126385f7a14c/rewrite-xml/src/main/java/org/openrewrite/xml/XsltTransformationVisitor.java#L85-L98 Image

Expected behavior

No change made at all, either because we correctly detect the throw in the try-with-resources close(), or because we do not make any changes for try-with-resources out of caution.

Example diff

From: rewrite-xml/src/main/java/org/openrewrite/xml/XsltTransformationVisitor.java

  import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.IOException;
import java.util.Objects;

import static org.openrewrite.Tree.randomId;
              transformer.transform(text, new StreamResult(os));
        return document.withRoot(Xml.Tag.build(os.toString().replace("\r", "")));
    }
-        } catch (IOException | TransformerException e) {
+        } catch (TransformerException e) {
    throw new RuntimeException("XSLT transformation exception: " + e.getMessage(), e);
}
}
              transformer.transform(text, new StreamResult(baos));
        return Xml.Tag.build(baos.toString());
    }
-        } catch (IOException | TransformerException e) {
+        } catch (TransformerException e) {
    throw new RuntimeException("XSLT transformation exception: " + e.getMessage(), e);
}
}

Recipes in example diff:

  • org.openrewrite.staticanalysis.UnnecessaryCatch

References:

  • View original result
  • Recipe ID: org.openrewrite.staticanalysis.UnnecessaryCatch
  • Recipe Name: Remove catch for a checked exception if the try block does not throw that exception
  • Repository: openrewrite/rewrite/main
  • Created at Wed Jul 30 2025 22:02:41 GMT+0200 (Central European Summer Time)

timtebeek avatar Jul 30 '25 20:07 timtebeek

Weirdly we have a matching unit test already; we have the latest version deployed already; yet I can't replicate the above in a unit test yet.

timtebeek avatar Jul 30 '25 21:07 timtebeek