Skip to content

Commit

Permalink
Specifically check for JavaType.MultiCatch
Browse files Browse the repository at this point in the history
  • Loading branch information
timtebeek committed Oct 22, 2024
1 parent 7364f62 commit 6b39457
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.*;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.TypeUtils;

import java.time.Duration;
import java.util.Set;
Expand All @@ -37,7 +40,7 @@ public String getDisplayName() {
@Override
public String getDescription() {
return "A `catch` clause that only rethrows the caught exception is unnecessary. " +
"Letting the exception bubble up as normal achieves the same result with less code.";
"Letting the exception bubble up as normal achieves the same result with less code.";
}

@Override
Expand Down Expand Up @@ -105,11 +108,18 @@ private boolean hasWiderExceptionType(J.Try.Catch aCatch, J.Try.Catch next) {

private boolean onlyRethrows(J.Try.Catch aCatch) {
if (aCatch.getBody().getStatements().size() != 1 ||
!(aCatch.getBody().getStatements().get(0) instanceof J.Throw)) {
!(aCatch.getBody().getStatements().get(0) instanceof J.Throw)) {
return false;
}

Expression exception = ((J.Throw) aCatch.getBody().getStatements().get(0)).getException();
JavaType catchParameterType = aCatch.getParameter().getType();
if (!(catchParameterType instanceof JavaType.MultiCatch)) {
JavaType.FullyQualified catchType = TypeUtils.asFullyQualified(catchParameterType);
if (catchType == null || !catchType.equals(exception.getType())) {
return false;
}
}
if (exception instanceof J.Identifier) {
return ((J.Identifier) exception).getSimpleName().equals(aCatch.getParameter().getTree().getVariables().get(0).getSimpleName());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,14 +165,40 @@ void foo() throws IOException {
}
}
""",
"""
"""
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
class A {
void foo() throws IOException {
new FileReader("").read();
}
}
"""
)
);
}

@Test
void multiCatchPreservedOnDifferentThrow() {
rewriteRun(
//language=java
java(
"""
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
class A {
void foo() throws IOException {
new FileReader("").read();
try {
new FileReader("").read();
} catch (FileNotFoundException e) {
throw e;
} catch(IOException | ArrayIndexOutOfBoundsException e) {
throw new IOException("another message", e);
}
}
}
"""
Expand Down

0 comments on commit 6b39457

Please sign in to comment.