Difference between e.printStackTrace and System.out.println(e)
The output stream used is not the same as pointed out by @Brian, but the level of detail is not the same either - you can try with the simple test below. Output:
With println
: you only know what exception has been thrown
java.lang.UnsupportedOperationException: Not yet implemented
With printStackTrace
: you also know what caused it (line numbers + call stack)
java.lang.UnsupportedOperationException: Not yet implemented
at javaapplication27.Test1.test(Test1.java:27)
at javaapplication27.Test1.main(Test1.java:19)
public static void main(String[] args){
try {
test();
} catch (UnsupportedOperationException e) {
System.out.println(e);
e.printStackTrace();
}
}
private static void test() {
throw new UnsupportedOperationException("Not yet implemented");
}
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.
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.