Maintaining a consistent link between the caught variable and the exception thrown in the corresponding try block brings clarity and predictability. Reassigning the caught variable disrupts this expectation and can lead to confusion. By refraining from these reassignments, developers can know that the variable encapsulates the essence of the original exception.
Non-Compliant Code Examples
publicclassFoo{publicvoidfoo(){try{// do something}catch(Exceptione){e=newNullPointerException();// should not reassign here}}}
Compliant Code Examples
publicclassFoo{publicvoidfoo(){try{// do something}catch(MyExceptione){newError=newRuntimeException();// created a new error variable}}}
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- java-best-practices # Rules to enforce Java best practices.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines