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

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


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)


It helps to trace the exception. For example you are writing some methods in your program and one of your methods causes bug. Then printstack will help you to identify which method causes the bug. Stack will help like this:

First your main method will be called and inserted to stack, then the second method will be called and inserted to the stack in LIFO order and if any error occurs somewhere inside any method then this stack will help to identify that method.