This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

Metadata

ID: java-best-practices/avoid-reassigning-catch-vars

Language: Java

Severity: Notice

Category: Best Practices

Description

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

public class Foo {
    public void foo() {
        try {
            // do something
        } catch (Exception e) {
            e = new NullPointerException(); // should not reassign here
        }
    }
}

Compliant Code Examples

public class Foo {
    public void foo() {
        try {
            // do something
        } catch (MyException e) {
            newError = new RuntimeException(); // created a new error variable
        }
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: Cyril-Bouchiat/add-vm-package-explorer-doc