Repository navigation
[java] Fix #6693: CloneMethodMustImplementCloneable false positive for local-var throw - #6885
Conversation
…-var throw
justThrowsCloneNotSupported() only recognized the exemption when the
clone() body was the single statement "throw new
CloneNotSupportedException();". A clone() that assigns the exception to
a local variable first and then throws it,
CloneNotSupportedException e = new CloneNotSupportedException();
throw e;
is semantically identical but has a body of size 2, so the check failed
and the rule reported a violation even though the class still doesn't
implement Cloneable on purpose.
Add throwsLocalCloneNotSupported() to recognize this two-statement form:
the first statement must declare a single local variable of type
CloneNotSupportedException, and the second must throw that same
variable.
Fixes pmd#6693
|
Compared to main: (comment created at 2026-09-06 16:46:49+00:00 for 6b04e87) |
…rows-local-var # Conflicts: # docs/pages/release_notes.md
There was a problem hiding this comment.
Thanks for the contribution. The implementation indeed fixes the specific case described in the linked issue, but I think we should first decide what the desired behavior of this rule is.
The rule description says
The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException.
One interpretation of that is that doing anything more complex than a single throw statement is not applicable for the exception, in which case the issue is invalid.
Another way to interpret it is that implementations are allowed if they contain no return and all their throw statements throw an instance of CloneNotSupportedException. That would allow e.g. a logging statement added to that method.
I think adjusting the rule implementation to follow this interpretation would be useful. Allowing only the one special case mentioned in #6693 seems too specific, such code violates the VariableCanBeInlined rule.
Walk the whole clone() method body instead of pattern-matching one specific two-statement shape. Exempt bodies with no return statement where every throw is (a subtype of) CloneNotSupportedException and at least one throw is present, so a no-op override isn't wrongly exempted.
|
Thanks for the detailed review — I agree with the second interpretation, and I've reworked the implementation to follow it. Instead of pattern-matching the one specific two-statement shape from #6693, the check now walks the whole method body (without crossing into nested/anonymous classes or lambdas, since their control flow isn't the enclosing
That last condition matters more than it looks: a naive "no return + all throws are CloneNotSupportedException" check is vacuously true for a body with zero throw statements, which would wrongly exempt a no-op This now covers cases beyond the original issue too — e.g. a logging call before the throw, or the throw sitting inside a try/catch — while still flagging methods that mix a You're also right that the shape this PR originally special-cased would itself trip All 26 rule test cases (20 existing + 6 new) pass, and I confirmed the new ones actually exercise the change by checking they fail against the old narrow implementation before restoring the fix. Let me know if you'd like the exemption scoped any differently (e.g. excluding |
…ntCloneable Covers a clone() body where an if/else has a CloneNotSupportedException throw in each branch (no fall-through, no single unconditional throw), exercising the "every throw statement" part of the broadened exemption in a shape not covered by the existing tests.
|
Thanks for the detailed feedback, @zbynek. I agree the broader interpretation is the right one. Gating on the one specific pattern from #6693 was too narrow, and as you point out, that pattern is arguably something I reworked It's implemented with Test coverage now includes the newly-permitted cases:
and cases that must still be flagged:
All 27 tests for this rule pass, and I ran the full One thing worth flagging rather than leaving for you to find later: this check is syntactic, not a full JLS reachability analysis. It handles the cases above correctly, but there's a case it under-reports: a void clone() {
if (someCondition) {
throw new CloneNotSupportedException();
}
System.out.println("done");
}The body has no There's already a proper JLS 14.21-style reachability analysis in the codebase, Pushed as two commits on the same branch: the reimplementation, plus one small commit adding the if/else multi-branch test. |
That's how I always understood that sentence.
I agree that allowing logging statements is a good thing. But your definition would allow an arbitrary combination of loops and other control statements, variable assignments and function calls. Is that really what we want? Where should we draw the line? |
I think the line should not be based on the content of the method, but on the possible outcome.
I'm mentioning explicit throw statements, because this was considered valid before and should still be valid (for this rule): protected Object clone() throws CloneNotSupportedException { // actually always throws IOOBE
throw new CloneNotSupportedException(List.of("fail").get(7));
}
That code would not compile. Method called |
But outcome includes side-effects. For example: That's not "only throws CloneNotSupportedException", is it? |
|
Well, side-effects are ignored in current implementation too 🤷 |
|
I'd argue that that's a bug that should be fixed. |
|
@zbynek good catch, and you're right -- I checked it directly rather than taking my own word for it: So a no-parameter On the old |
|
I'm still concerned that this change will allow too much and introduce a bunch of false negatives. How about something like this: A clone method must...
|
|
I think the main purpose of the rule is to enforce that "every clone() method should be in a class implementing I agree with your point that class A {
@Override
protected final Object clone() {
System.setErr(System.out); // bad
throw new CloneNotSupportedException();
}to class A implements Cloneable {
@Override
protected final Object clone() {
System.setErr(System.out); // good, we're Cloneable now, rule name says ...MustImplementCloneable
throw new CloneNotSupportedException();
}which does not seem helpful. Technically even insisting that the method's throw statements all throw |
|
Yeah, ok. I think you're right. Just to explain where I was coming from. I consider the Cloneable interface to be fundamentally broken. If you've got the 3rd edition of "Effective Java" lying around, see Item 13. That's why I insisted so much on a literal interpretation of the exceptional part of the rule. But I guess I shouldn't shoehorn my opinion into a rule that is fundamentally about something else. |
|
Thanks @UncleOwen — and to be explicit about it, I'm not going to implement the six-bullet version, since you've withdrawn it. That leaves one thing I'd rather ask about than guess at, because I measured it and it cuts against the obvious reading. @zbynek, your 07-25 summary was:
I built that gate and ran it. It reports the snippet you posted on 07-23 — the one you said "was considered valid before and should still be valid (for this rule)": public class Foo {
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException(List.of("fail").get(7));
}
}Current head: 0 violations. With the finality gate: 1. The method is The part I think neither of you has had reason to look at: the finality condition in the rule's description has never actually been implemented. The pre-PR body of the check was body.size() == 1 && body.getChild(0)...filter(it -> TypeTestUtil.isA(CloneNotSupportedException.class, it)).nonEmpty()with no modifier inspection anywhere in the file — So, concretely: add the finality gate in this PR (with a Some measurements, so it's answerable in one round either way:
Two smaller things while you're here: My 07-23 question is still open — the pre-existing non-compilable And a note rather than a request: every workflow run on this branch has sat at |
The snippet added for "no throw statement at all is not exempted" didn't compile, on two counts: the method was package-private, which assigns weaker access than the inherited protected Object.clone(), and the body fell off the end of a method declared to return Object. `protected final Object clone()` with a `while (true)` body fixes both while keeping the case exactly as pointed: no return statement, no throw statement, non-Cloneable class, so the exemption's "at least one throw" condition is what decides it. Still reports 1. Leaves the pre-existing `void clone()` cases alone -- those predate this PR and zbynek offered to handle them separately.
|
@zbynek I'll leave this one to you. |
…rows-local-var Resolves the release-notes conflict: re-adds the pmd#6693 bullet under the current unreleased java-errorprone section, in issue-number order. The rule and test files are unchanged upstream since the merge base.
|
Thanks for the approval @zbynek — the branch had gone stale in the meantime, so I've merged current The only conflict was Merged rather than rebased so the approval isn't dismissed. Ready when you are. |
|
Merged current The conflict was only in that file: my one entry was sitting in the old accumulated list, so I took the fresh post-release file and re-added the Used a merge rather than a rebase so the existing approval is not dismissed.
|
UncleOwen
left a comment
There was a problem hiding this comment.
Thanks.
I moved your tests to the end and removed one I found misleading. It was kind-of implying we're handling
try {
throw new Foo();
} catch (Foo ex) {
throw new CloneNotSupportedException();
}
correctly, which we don't. But I think this is good enough for now.
Fixes #6693.
justThrowsCloneNotSupported()only exempts aclone()method whose body is the single statementthrow new CloneNotSupportedException();. A body that instead assigns the exception to a local variable first and then throws it,is semantically identical but has
body.size() == 2, so the exemption check fails and the class is wrongly flagged for not implementingCloneable.Adds
throwsLocalCloneNotSupported, checked when the body has exactly two statements: the first must be a local variable declaration of a single variable whose initializer is-aCloneNotSupportedException, and the second must be athrowof that same variable (matched by symbol equality). Added a regression test case matching the issue's second case.