javaexceptionprintstacktrace

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?


Solution

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