My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping @Yeyhi.com

Pages










Friday, May 29, 2020

PMD error Avoid printStackTrace use logger call instead

Suppose you have a simple Try catch block in Java eg:

try {
  testsReader.readTestConfigurationJson();
  testsReader.readDeclarativeTestJson();

} catch (IOException e) {
  e.printStackTrace();
}


Running Java PMD during compilation will give you following error:

<pmd xmlns="http://pmd.sourceforge.net/report/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pmd.sourceforge.net/report/2.0.0 http://pmd.sourceforge.net/report_2_0_0.xsd" version="6.8.0" timestamp="2020-05-29T14:37:13.048"> <file name="/Users/mfaiz/<path>/platform/integration/test/framework/controller/StartController.java"> <violation beginline="71" endline="71" begincolumn="7" endcolumn="25" rule="AvoidPrintStackTrace" ruleset="Best Practices"package="<path>.integration.test.framework.controller" class="StartController" method="start" externalInfoUrl="https://pmd.github.io/pmd-6.8.0/pmd_rules_java_bestpractices.html#avoidprintstacktrace" priority="3"> Avoid printStackTrace(); use a logger call instead. </violation> </file> </pmd>

This is basically a violation of AvoidPrintStackTrace rule.


But, if you remove the e.printStacktrace() then you will get following pmd error:

<pmd xmlns="http://pmd.sourceforge.net/report/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pmd.sourceforge.net/report/2.0.0 http://pmd.sourceforge.net/report_2_0_0.xsd" version="6.8.0" timestamp="2020-05-29T14:31:59.579"> <file name="/Users/mfaiz/<path>/integration/test/framework/controller/StartController.java"> <violation beginline="70" endline="72" begincolumn="7" endcolumn="5" rule="EmptyCatchBlock" ruleset="Error Prone" package="<path>test.framework.controller"class="StartController" method="start" externalInfoUrl="https://pmd.github.io/pmd-6.8.0/pmd_rules_java_errorprone.html#emptycatchblock" priority="3">Avoid empty catch blocks</violation> </file> </pmd>



Solution:

Hence, the best solution is to use a logger.
It means you should use logging framework like logback or log4j and instead of printing exceptions directly:

e.printStackTrace();
    you should log them using this frameworks' API:

Eg:  log.error("Ops!", e);
Logging frameworks give you a lot of flexibility, e.g. you can choose whether you want to log to console or file - or maybe skip some messages if you find them no longer relevant in some environment.


But if you are in initial stages of development and want to postpone logging at this time then you can do the following trick.

Think!!!!
I will update the trick in next post :)

No comments:

Post a Comment