This product is not supported for your selected Datadog site. ().
Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
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
classFoo{voidbar(){try{// removed for brevity}catch(MyExceptionmyException){myException.printStackTrace();}catch(Exceptione){if("foo"!="bar"){e.printStackTrace();}}}}
Compliant Code Examples
classFoo{voidbar(){try{// removed for brevity}catch(MyExceptionmyException){myException.printStackTrace();}catch(Exceptione){if("foo"!="bar"){e.printStackTrace();}}}}
importjava.util.logging.Logger;classFoo{privatestaticfinalLoggerlogger=Logger.getLogger(Foo.class.getName());voidbar(){try{// Code that may throw an exceptionthrownewRuntimeException("Something went wrong!");}catch(Exceptione){// Log the exception using the Java loggerlogger.severe("An error occurred:");logger.severe(e.toString());if("foo"!="bar"){// Log the exception again if neededlogger.severe("An error occurred in an additional context:");logger.severe(e.toString());}}}}
Seamless integrations. Try Datadog Code Security
Datadog Code Security
Try this rule and analyze your code with Datadog Code Security
How to use this rule
1
2
rulesets:- java-best-practices # Rules to enforce Java best practices.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Security scans to your CI pipelines