GeezerVison is showing github.com — [java] New Rule: AvoidReassigningCatchVariables · Issue #2471 · pmd/pmd
[java] New Rule: AvoidReassigningCatchVariables #2471
Description
Proposed Rule Name: AvoidReassigningCatchVariables
Proposed Category: Best Practices
Description:
The rule AvoidReassigningParameters flags a problem when code assigns a value to a method parameter. Here is the reason in documentation.
Reassigning values to incoming parameters is not recommended. Use temporary local variables instead.
This new rule AvoidReassigningCatchVariables will flag a problem when code assigns a value to the catch variable.
I do not know why AvoidReassigningParameters exists. I assume that AvoidReassigningCatchVariables should exist for the same reason.
Code Sample:
...
catch (Exception e)
{
e = new Exception("Hello World", e); // This should be flagged as a problem
}
...
// Fixed code
...
catch (Exception e)
{
Exception wrap;
wrap = new Exception("Hello World", e);
}
Possible Properties:
This rule does not need any properties.
See also:
Activity
oowekyala commented on May 7, 2020
One justification this rule could have, that is more solid than that of AvoidReassigningParameters, is that exception parameters in a multicatch block are implicitly final. So if you do
catch (IOException e)
{
e = new Exception("Hello World", e);
}
adding an exception type will make it uncompilable:
catch (IOException | TokenMgrError e)
{
e = new Exception("Hello World", e); // e is implicitly final, this doesn't compile
}adangel commented on May 8, 2020
On the other hand - if the compiler already complains, then we don't need a rule 😄 - Update - I think, I get it now: the rule would prevent this compile error by flagging it even before (when assignment would be possible), so that you actually can add later another exception to the case and make it a multicatch.
Reassigning parameters or catch variables might be surprising. It depends on what you are used to (principle of least surprise). If you assume, that the parameters/catch vars always have their initial value when entering the block, then you might make false decisions, if this is not the case (e.g. it might not be anymore the original exception with the correct/original stacktrace). See also #2219.
changed the title
[-][java] AvoidReassigningCatchVariables[/-] [+][java] New Rule: AvoidReassigningCatchVariables[/+] on Jul 31, 2020added a commit that references this issue
on Jul 31, 2020This issue will close once commit c447319 is merged into the 'main' branch.c447319
Metadata
Metadata
Development
No branches or pull requestsIssue actions