Difference between printStackTrace() and toString()

后端 未结 7 1425
甜味超标
甜味超标 2020-12-08 02:06

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:

7条回答
  •  猫巷女王i
    2020-12-08 02:24

    No, there's a huge difference. If you just call toString, it won't print anything - it will just return a string. A catch block of just e.toString(); is useless. (There's also the matter of the stack trace, as Martijn pointed out.)

    Personally I wouldn't use either though - I'd use a logging library (log4j, java.util.logging etc) which takes the Throwable itself as a parameter, and will format it usefully - including the stack trace, potentially truncated to avoid repetition.

提交回复
热议问题