Skip to content

Commit fa1d3c3

Browse files
timtebeekclaude
andcommitted
Fix OnlyCatchDeclaredExceptions to skip generic type variables
When a method throws a generic type parameter (e.g., `<TE extends Throwable>`), the recipe should not attempt to replace the generic catch block. Generic type variables cannot be used in multi-catch blocks and attempting to do so causes an IllegalArgumentException during JavaTemplate parsing. This fix adds a check to skip transformation when any of the thrown exceptions is a generic type variable, ensuring the recipe only operates on concrete exception types. Fixes #715 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 21ad269 commit fa1d3c3

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public J.Try visitTry(J.Try aTry, ExecutionContext ctx) {
6464
// Find declared thrown exceptions that are not already specifically caught
6565
Set<JavaType> declaredThrown = getDeclaredThrownExceptions(t);
6666
declaredThrown.removeAll(getCaughtExceptions(t));
67-
if (!declaredThrown.isEmpty()) {
67+
if (!declaredThrown.isEmpty() && !containsGenericTypeVariable(declaredThrown)) {
6868
return multiCatchWithDeclaredExceptions(c, declaredThrown);
6969
}
7070
}
@@ -81,6 +81,15 @@ private boolean isGenericCatch(J.Try.Catch aCatch) {
8181
return false;
8282
}
8383

84+
private boolean containsGenericTypeVariable(Set<JavaType> types) {
85+
for (JavaType type : types) {
86+
if (type instanceof JavaType.GenericTypeVariable) {
87+
return true;
88+
}
89+
}
90+
return false;
91+
}
92+
8493
private Set<JavaType> getCaughtExceptions(J.Try aTry) {
8594
Set<JavaType> caughtExceptions = new HashSet<>();
8695
for (J.Try.Catch c : aTry.getCatches()) {

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,4 +453,30 @@ void doSomething() {
453453
)
454454
);
455455
}
456+
457+
@Test
458+
@org.openrewrite.Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/715")
459+
void doNotChangeWhenThrownExceptionIsGeneric() {
460+
rewriteRun(
461+
spec -> spec.parser(JavaParser.fromJavaVersion()),
462+
//language=java
463+
java(
464+
"""
465+
interface ThrowsGenerics<TE extends Throwable> {
466+
void get() throws TE;
467+
}
468+
469+
class MyService {
470+
void doSomething(ThrowsGenerics<Exception> t) {
471+
try {
472+
t.get();
473+
} catch (Exception e) {
474+
// Should not be changed - thrown exception is generic
475+
}
476+
}
477+
}
478+
"""
479+
)
480+
);
481+
}
456482
}

0 commit comments

Comments
 (0)