Skip to content

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 #677

@timtebeek

Description

@timtebeek

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions