Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 487
imulsion Avatar asked Aug 23 '12 15:08

imulsion


People also ask

What does e printStackTrace mean in java?

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.

What can I use instead of E printStackTrace?

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.

What is the difference between getStackTrace and printStackTrace?

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.

How do I print stack trace with system out?

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.


1 Answers

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"); } 
like image 175
assylias Avatar answered Oct 05 '22 17:10

assylias