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

前端 未结 6 1515
清歌不尽
清歌不尽 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:28

    If you use System.out.println, then you're dumping your errors to the stdout, not stderr.

    It's traditional to dump errors to standard error, so you can filter normal successful output from the error output. It's a common practise for command-line utilities and consequently a good idea to follow.

    e.g.

    myCommand 2> /tmp/errors > /tmp/results
    

    will write errors to one log, and the results to another. Depending on your shell/invoking process etc. you can combine this info, throw errors away, react if any errors are thrown etc. See here for more info.

    Using printStackTrace() is a good idea since you're dumping out where the exception took place. This is often invaluable for tracking errors that are unexpected since it'll give you a direct (if verbose) pointer to where exactly you ran into an error.

提交回复
热议问题