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?
It's a method on
Exception
instances that prints the stack trace of the instance toSystem.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:
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:
Calling
println(e)
:Calling
e.printStackTrace()
:printStackTrace
is a method of theThrowable
class. This method displays error message in the console; where we are getting the exception in the source code. These methods can be used with catch block and they describe:The three methods which describe the exception on the console (in which printStackTrace is one of them) are:
printStackTrace()
toString()
getMessage()
Example: