If I use a logger in the case of known exceptions, what's wrong with e.printStackTrace()
for an unknown exception ?
I'm always told not to do this - but not given a reason
example below
try {
dostuff();
} catch (AException ae) {
logger.error("ae happened");
} catch (BException be) {
logger.error("be happened");
} catch (CException ce) {
logger.error("ce happened");
} catch (Exception e) {
e.printStackTrace();
}
It is not bad practice because something is 'wrong' about PrintStackTrace(), but because it's 'code smell'. Most of the time the PrintStackTrace() call is there because somebody failed to properly handle the exception.
The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.
It's probably because printStackTrace() doesn't really handle the error as much as it just dumps the stack in the console. It acts as a placeholder until you replace it with proper error handling (if it is needed at all) and replace the output with a logger of some sort.
e. printStackTrace() is generally discouraged because it just prints out the stack trace to standard error. Because of this you can't really control where this output goes. The better thing to do is to use a logging framework (logback, slf4j, java.
IMHO, You should
Because it doesn't use the logger system, it goes directly to the stderr
which has to be avoided.
edit: why writing directly to stderr has to be avoided ?
In answer to your question, @shinynewbike, I have slightly modifed my answer. What it has to be avoided is to write directly to stderr
without using a logger
capability.
loggers
provide useful features to change logging traces by priority and packages, among other things they also allow to redirect traces to different output mechanisms ... queues, files, databases, streams ...
When you write directly to System.err
or System.out
then you lose these features, and what is worse if you mix logger
and System.err.write
you might end up getting traces in different 'files' which will make debugging your system difficult.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With