How to store printStackTrace into a string [duplicate]

How can I get the e.printStackTrace() and store it into a String variable? I want to use the string generated by e.printStackTrace() later in my program.

I'm still new to Java so I'm not too familiar with StringWriter that I think will be the solution. Or if you have any other ideas please let me know. Thanks


Solution 1:

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:

  • StringWriter
  • PrintWriter
  • Throwable

Solution 2:

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

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

Internally, this does what @Zach L suggests.