Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
299 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...