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

Venkat picture Venkat · Apr 1, 2010 · Viewed 414.5k times · Source

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?

Answer

Joachim Sauer picture Joachim Sauer · Apr 1, 2010

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();
}