Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of printStackTrace() method in Java?

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?

like image 783
Venkat Avatar asked Apr 01 '10 12:04

Venkat


People also ask

Why we must call printStackTrace () in catch block?

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.

Why we should not use printStackTrace?

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.

What we can use instead of printStackTrace?

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.


2 Answers

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);.

like image 105
Joachim Sauer Avatar answered Oct 19 '22 16:10

Joachim Sauer


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) 
like image 23
Jens Bodal Avatar answered Oct 19 '22 18:10

Jens Bodal