I have used e.printStackTrace
in one of my Java applications. However, I read in some forum that we should avoid using printStackTrace()
. Could somebody explain to me why I should avoid using e.printStackTrace()
and what are the alternatives to it?
Please share the piece of code for an alternative to e.printStackTrace()

- 41
- 1
- 2
- 4
-
3Does this answer your question? [Why is exception.printStackTrace() considered bad practice?](https://stackoverflow.com/questions/7469316/why-is-exception-printstacktrace-considered-bad-practice) – Turamarth Nov 18 '20 at 11:57
3 Answers
Loggers should be used instead of printing the whole stack trace on stream. e.printStackTrace() prints a Throwable and its stack trace to stream which could inadvertently expose sensitive information.
Loggers should be used instead to print Throwables, as they have many advantages.
more info : https://owasp.org/www-project-top-ten/2017/A3_2017-Sensitive_Data_Exposure.html

- 141
- 7
I usually log errors this way:
} catch (IOException ex) {
log.log(Level.WARNING, ex.getMessage(), ex);
}
If you use lombok, you can add logger to your class with @Log
annotation on class.

- 352
- 1
- 9
You should avoid it because it is better to use a logger like Log4j, so that you can write logs in a file & manage the logging better.
Indeed, the method
e.printStackTrace()
is used to print the stack of the exception directly in the console, and that (for a production application) is bad.

- 39
- 4