How to store printStackTrace into a string [duplicate] How to store printStackTrace into a string [duplicate] java java

How to store printStackTrace into a string [duplicate]


Something along the lines of

StringWriter errors = new StringWriter();ex.printStackTrace(new PrintWriter(errors));return errors.toString();

Ought to be what you need.

Relevant documentation:


Guava makes this easy with Throwables.getStackTraceAsString(Throwable):

Exception e = ...String stackTrace = Throwables.getStackTraceAsString(e);

Internally, this does what @Zach L suggests.


You can use the ExceptionUtils.getStackTrace(Throwable t); from Apache Commons 3 class org.apache.commons.lang3.exception.ExceptionUtils.

http://commons.apache.org/proper/commons-lang/

ExceptionUtils.getStackTrace(Throwable t)

Code example:

try {  // your code here} catch(Exception e) {  String s = ExceptionUtils.getStackTrace(e);}