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