What is the use of printStackTrace() method in Java?
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'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);
.