My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping

Friday, May 29, 2020

PMD error Avoid printStackTrace use logger call instead

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

try {

} catch (IOException e) {

Running Java PMD during compilation will give you following error:

<pmd xmlns="" xmlns:xsi="" xsi:schemaLocation="" version="6.8.0" timestamp="2020-05-29T14:37:13.048"> <file name="/Users/mfaiz/<path>/platform/integration/test/framework/controller/"> <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="" 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="" xmlns:xsi="" xsi:schemaLocation="" version="6.8.0" timestamp="2020-05-29T14:31:59.579"> <file name="/Users/mfaiz/<path>/integration/test/framework/controller/"> <violation beginline="70" endline="72" begincolumn="7" endcolumn="5" rule="EmptyCatchBlock" ruleset="Error Prone" package="<path>test.framework.controller"class="StartController" method="start" externalInfoUrl="" priority="3">Avoid empty catch blocks</violation> </file> </pmd>


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:

    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.

I will update the trick in next post :)

No comments:

Post a Comment