Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between printStackTrace() and toString()

Tags:

java

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() } 
like image 615
Andreas Avatar asked Apr 12 '12 09:04

Andreas


People also ask

What is the use of printStackTrace () method?

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.

What is the difference between getStackTrace and printStackTrace?

Class Throwable offers a printStackTrace method that outputs to the standard error stream the stack trace (discussed in Section 13.3). Often, this is helpful in testing and debugging. Class Throwable also provides a getStackTrace method that retrieves stack-trace information that might be printed by printStackTrace.

What can I use instead of E printStackTrace?

Loggers should be used instead of printing the whole stack trace on stream. e. printStackTrace() prints a Throwable and its stack trace to stream which could inadvertently expose sensitive information. Loggers should be used instead to print Throwables, as they have many advantages.

Why we should not use e printStackTrace ()?

e. printStackTrace() is generally discouraged because it just prints out the stack trace to standard error. Because of this you can't really control where this output goes. The better thing to do is to use a logging framework (logback, slf4j, java.


1 Answers

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()):

java.io.FileNotFoundException: yourFile.txt (The system cannot find the file specified) 

Example of printStackTrace():

java.io.FileNotFoundException: yourFile.txt (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.(FileInputStream.java:106) at java.io.FileReader.(FileReader.java:55) at ReadFromFile.main(ReadFromFile.java:14) 

To make a string of the whole stacktrace, I usually use this method:

public static String exceptionStacktraceToString(Exception e) {     ByteArrayOutputStream baos = new ByteArrayOutputStream();     PrintStream ps = new PrintStream(baos);     e.printStackTrace(ps);     ps.close();     return baos.toString(); } 

Also note that simply calling toString() simply returns a string, and won't print anything out.

like image 162
Martijn Courteaux Avatar answered Sep 19 '22 23:09

Martijn Courteaux