Don't reassign a catch variable

このページは日本語には対応しておりません。随時翻訳に取り組んでいます。翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください。

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: may/unit-testing