Avoid using printStackTrace()

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: java-best-practices/avoid-printstacktrace

Language: Java

Severity: Warning

Category: Best Practices

Description

Use a logging framework instead of printStackTrace() when handling exceptions. printStackTrace() can be useful during development for quick debugging, but it is not suitable for production code.

Non-Compliant Code Examples

class Foo {
    void bar() {
        try {
            // removed for brevity
        } catch (MyException myException) {
            myException.printStackTrace();
        } catch (Exception e) {
            if ("foo" != "bar") {
                e.printStackTrace();               
            }
        }
    }
}

Compliant Code Examples

class Foo {
    void bar() {
        try {
            // removed for brevity
        } catch (MyException myException) {
            myException.printStackTrace();
        } catch (Exception e) {
            if ("foo" != "bar") {
                e.printStackTrace();               
            }
        }
    }
}
import java.util.logging.Logger;

class Foo {
    private static final Logger logger = Logger.getLogger(Foo.class.getName());

    void bar() {
        try {
            // Code that may throw an exception
            throw new RuntimeException("Something went wrong!");
        } catch (Exception e) {
            // Log the exception using the Java logger
            logger.severe("An error occurred:");
            logger.severe(e.toString());

            if ("foo" != "bar") {
                // Log the exception again if needed
                logger.severe("An error occurred in an additional context:");
                logger.severe(e.toString());
            }
        }
    }
}
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: mervebolat/span-id-preprocessing