I am going through a socket program. In it, printStackTrace
is called on the IOException
object in the catch block.
What does printStackTrace()
actually do?
catch(IOException ioe) { ioe.printStackTrace(); }
I am unaware of its purpose. What is it used for?
printStackTrace() helps the programmer to understand where the actual problem occurred. It helps to trace the exception. it is printStackTrace() method of Throwable class inherited by every exception class. This method prints the same message of e object and also the line number where the exception occurred.
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.
Instead of doing this you are advised using a logging framework (or a wrapper around multiple logging frameworks, like Apache Commons Logging) and log the exception using that framework (e.g. logger.
It's a method on Exception
instances that prints the stack trace of the instance to System.err
.
It's a very simple, but very useful tool for diagnosing an exceptions. It tells you what happened and where in the code this happened.
Here's an example of how it might be used in practice:
try { // ... } catch (SomeException e) { e.printStackTrace(); }
Note that in "serious production code" you usually don't want to do this, for various reasons (such as System.out
being less useful and not thread safe). In those cases you usually use some log framework that provides the same (or very similar) output using a command like log.error("Error during frobnication", e);
.
I was kind of curious about this too, so I just put together a little sample code where you can see what it is doing:
try { throw new NullPointerException(); } catch (NullPointerException e) { System.out.println(e); } try { throw new IOException(); } catch (IOException e) { e.printStackTrace(); } System.exit(0);
Calling println(e)
:
java.lang.NullPointerException
Calling e.printStackTrace()
:
java.io.IOException at package.Test.main(Test.java:74)
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