I’m curious as to what the difference is between printStackTrace() and toString().
At first sight, they seem to do the exact same thing.
Code:
try {
// Some code
} catch (Exception e)
e.printStackTrace();
// OR
e.toString()
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, there is an important difference! Using toString, you only have the type of the exception and the error message. Using printStackTrace() you get the whole stacktrace of an exception, which is very helpful for debugging.
Example of System.out.println(toString()):
Example of printStackTrace():
To make a string of the whole stacktrace, I usually use this method:
Also note that simply calling
toString()simply returns a string, and won’t print anything out.