Skip to content

Commit a095673

Browse files
timtebeekTim te Beek
andauthored
Fix UnnecessaryThrows to check actual close() method exceptions (#812)
The recipe was incorrectly removing throws declarations from methods using try-with-resources because it made blanket assumptions that all Closeable types throw IOException and all AutoCloseable types throw Exception. Instead, the fix looks up the actual close() method on the resource type and checks what exceptions it declares, using the same mechanism already used for method invocations. Fixes #728 Co-authored-by: Tim te Beek <tim@mac.home>
1 parent a32c4e3 commit a095673

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/main/java/org/openrewrite/staticanalysis/UnnecessaryThrows.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,12 @@ public J.Try.Resource visitTryResource(J.Try.Resource tryResource, ExecutionCont
7979

8080
JavaType.FullyQualified resourceType = TypeUtils.asFullyQualified(resource.getType());
8181
if (resourceType != null) {
82-
if (TypeUtils.isAssignableTo(JavaType.ShallowClass.build("java.io.Closeable"), resourceType)) {
83-
unusedThrows.remove(JavaType.ShallowClass.build("java.io.IOException"));
84-
} else if (TypeUtils.isAssignableTo(JavaType.ShallowClass.build("java.lang.AutoCloseable"), resourceType)) {
85-
unusedThrows.remove(JavaType.ShallowClass.build("java.lang.Exception"));
82+
// Find the close() method on the resource type to get its actual thrown exceptions
83+
for (JavaType.Method method : resourceType.getMethods()) {
84+
if ("close".equals(method.getName()) && method.getParameterTypes().isEmpty()) {
85+
removeThrownTypes(method);
86+
break;
87+
}
8688
}
8789
}
8890

src/test/java/org/openrewrite/staticanalysis/UnnecessaryThrowsTest.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,27 @@ public <E extends Exception> void accept(Class<E> e) throws E {
8585
);
8686
}
8787

88+
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/728")
89+
@SuppressWarnings("EmptyTryBlock")
90+
@Test
91+
void necessaryThrowsFromInputStreamClose() {
92+
rewriteRun(
93+
//language=java
94+
java(
95+
"""
96+
import java.io.InputStream;
97+
98+
class Test {
99+
void customStripSpaceXSL() throws Exception {
100+
try (InputStream is = getClass().getClassLoader().getResourceAsStream("foo.xsl")) {
101+
}
102+
}
103+
}
104+
"""
105+
)
106+
);
107+
}
108+
88109
@Issue("https://github.com/openrewrite/rewrite/issues/631")
89110
@SuppressWarnings("EmptyTryBlock")
90111
@Test

0 commit comments

Comments
 (0)