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());
            }
        }
    }
}