이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다.
현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.

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
        }
    }
}
PREVIEWING: aliciascott/DOCS-9725-Cloudcraft