pmd icon indicating copy to clipboard operation
pmd copied to clipboard

[java] UnnecessaryLocalBeforeReturn - false positive with catch clause

Open ben-manes opened this issue 3 years ago • 2 comments

Affects PMD Version:

Rule: UnnecessaryLocalBeforeReturn: Consider simply returning the value vs storing it in local variable 'e'

Description: When upgrading to 6.52.0 (from 6.51.0), this incorrectly flagged a caught exception that was returned. This is certainly not the nicest code or a good style, but was necessary for conforming to a service provider's interface. If not for constraints and being one-off code, a Try data type have been a nicer abstraction for this case, but I digress.

Code Sample demonstrating the issue: A simplified version of the code that flags e as unnecessary.

private @Nullable Exception attempt(Runnable task) {
  try {
    task.run();
    return null;
  } catch (Exception e) {
    return e;
  }
}

Expected outcome:

PMD reports a violation at line return e, but that's wrong. That's a false positive.

Running PMD through: Gradle

ben-manes avatar Nov 26 '22 18:11 ben-manes

Hi. Is there a workaround to handle this issue until we get the final solution? I have exactly the same scenario as @ben-manes.

kaleemsagard avatar Jul 24 '23 19:07 kaleemsagard

You can annotate the method with @SuppressWarnings("PMD.UnnecessaryLocalBeforeReturn").

ben-manes avatar Jul 24 '23 19:07 ben-manes