Probably a newbie question, but everyone seems to use e.printStackTrace()
, but I have always used System.out.println(e)
when exception handling. What is the difference and why is e.printStackTrace()
preferable?
The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.
Loggers should be used instead of printing the whole stack trace on stream. e. printStackTrace() prints a Throwable and its stack trace to stream which could inadvertently expose sensitive information. Loggers should be used instead to print Throwables, as they have many advantages.
Class Throwable offers a printStackTrace method that outputs to the standard error stream the stack trace (discussed in Section 13.3). Often, this is helpful in testing and debugging. Class Throwable also provides a getStackTrace method that retrieves stack-trace information that might be printed by printStackTrace.
The printStackTrace() method of Java. lang. Throwable class used to print this Throwable along with other details like class name and line number where the exception occurred means its backtrace. This method prints a stack trace for this Throwable object on the standard error output stream.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With