Print Exception Stack Trace

How to print an exception stack trace to a stream other than stderr? One way I found is to use getStackTrace () and print the entire list in the stream.

+67
java exception
Jul 25 '11 at 10:10
source share
8 answers

Throwable.printStackTrace(..) can accept a PrintWriter or Throwable.printStackTrace(..) argument:

 } catch (Exception ex) { ex.printStackTrace(new java.io.PrintStream(yourOutputStream)); } 

However, consider using a logger interface such as SLF4J with a logging implementation such as LOGBack or log4j .

+55
Jul 25 2018-11-22T00:
source share

Not pretty, but the solution nonetheless:

 StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter( writer ); exception.printStackTrace( printWriter ); printWriter.flush(); String stackTrace = writer.toString(); 
+68
Jul 25 '11 at 10:14
source share

There is an alternative form of Throwable.printStackTrace () that takes a print stream as an argument. http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)

eg.

 catch(Exception e) { e.printStackTrace(System.out); } 

This will output the stack trace to std instead of the std error.

+66
Jul 25 '11 at 10:14
source share

For minimalists android dev: Log.getStackTraceString(exception)

+8
Dec 06 '15 at 16:28
source share

I created a method that helps with getting stackTrace:

 private static String getStackTrace(Exception ex) { StringBuffer sb = new StringBuffer(500); StackTraceElement[] st = ex.getStackTrace(); sb.append(ex.getClass().getName() + ": " + ex.getMessage() + "\n"); for (int i = 0; i < st.length; i++) { sb.append("\t at " + st[i].toString() + "\n"); } return sb.toString(); } 
+3
Mar 15 '16 at 18:40
source share

The Throwable class provides two methods called printStackTrace , which accepts PrintWriter and one that accepts PrintStream , which prints the stack trace to the stream. Consider using one of them.

+2
Jul 25 '11 at 10:14
source share

See javadoc

 out = some stream ... try { } catch ( Exception cause ) { cause . printStrackTrace ( new PrintStream ( out ) ) ; } 
+1
Jul 25 '11 at 10:14
source share

Apache commons provides a utility for converting stack traces from cast to string.

Using:

 ExceptionUtils.getStackTrace(e) 

For full documentation, see https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html.

0
Mar 20 '18 at 15:43
source share



All Articles