Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import java.time.Duration;
import java.util.*;

import static org.openrewrite.java.tree.J.Modifier.Type.*;

public class UnnecessaryThrows extends Recipe {

@Override
Expand Down Expand Up @@ -146,6 +148,11 @@ private Set<JavaType.FullyQualified> findExceptionCandidates(J.@Nullable MethodD
return Collections.emptySet();
}

// Do not change the API of methods intended for overriding.
if (method.hasModifier(Protected) && !method.getMethodType().isOverride()) {
return Collections.emptySet();
}

//Collect all checked exceptions.
Set<JavaType.FullyQualified> candidates = new TreeSet<>(Comparator.comparing(JavaType.FullyQualified::getFullyQualifiedName));

Expand All @@ -166,9 +173,9 @@ private Set<JavaType.FullyQualified> findExceptionCandidates(J.@Nullable MethodD

//noinspection ConstantConditions
if ((method.getMethodType().getDeclaringType() != null && method.getMethodType().getDeclaringType().getFlags().contains(Flag.Final)) ||
method.isAbstract() || method.hasModifier(J.Modifier.Type.Static) ||
method.hasModifier(J.Modifier.Type.Private) ||
method.hasModifier(J.Modifier.Type.Final)) {
method.isAbstract() || method.hasModifier(Static) ||
method.hasModifier(Private) ||
method.hasModifier(Final)) {
//Consider all checked exceptions as candidates if the type/method are final or the method is private or static.
return candidates;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,4 +395,51 @@ public static class MyException extends Exception { }
)
);
}

@Issue("https://github.com/apache/maven/pull/2291")
@Test
void retainProtectedNonOverrides() {
rewriteRun(
//language=java
java(
"""
import java.io.FileNotFoundException;
class A {
// Someone marked this protected, and added exceptions that implementers can optionally use
protected void method() throws FileNotFoundException {
}
}
"""
),
java(
"""
import java.io.FileNotFoundException;
class B extends A {
@Override
protected void method() throws FileNotFoundException {
throw new FileNotFoundException();
}
}
"""
),
java(
"""
import java.io.FileNotFoundException;
class C extends A {
@Override
protected void method() throws FileNotFoundException {
}
}
""",
// Expected to remove here, as we override, but do not use the exceptions
"""
class C extends A {
@Override
protected void method() {
}
}
"""
)
);
}
}
Loading