Difference between e.printStackTrace and System.out.println(e)

前端 未结 6 1563
清歌不尽
清歌不尽 2021-01-31 17:05

Probably a newbie question, but everyone seems to use e.printStackTrace(), but I have always used System.out.println(e) when exception handling. What i

6条回答
  •  不要未来只要你来
    2021-01-31 17:46

    System.out.println(e) is equivalent to System.out.println(e.toString()): System.out is a PrintStream, PrintStream.println(Object o) calls PrintStream.println(o.toString()).

    e.toString() returns the name of the class, and the exception's getLocalizedMessage().

    e.printStackTrace() writes that information to System.err (not System.out) and also a stack trace, that is, the chain of methods that led to the exception. This is useful information.

    I've often thought it would be nice if there was a method that returns a String containing the info that's output by e.printStackTrace(). Since there isn't you have to use e.getStackTrace() and write your own routine to output the resulting array of StackTraceElements.

提交回复
热议问题