Save Exception StackTrace to a String

How to convert the stacktrace of an exception to string? Sometimes I need to save it as a string so I can fit it into certain API. The following is how I would do it. The resulted string contains the same information you would normally see when the stacktrace is printed. All nested causal exceptions should also be included.

public String stackTraceToString(Throwable e) {
String retValue = null;
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
retValue = sw.toString();
} finally {
try {
if(pw != null) pw.close();
if(sw != null) sw.close();
} catch (IOException ignore) {}
return retValue;


Anonymous said...

Technically the call for
if(sw != null) sw.close();
is unnecesary, as pw decorates sw, so when
pw is closed, so is sw too.

Anonymous said...

See commons lang


Anonymous said...

public static String getException(Exception e )
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
return w.toString();

JSnapshot Team said...

You could find that having just a stack trace is not enough to find the reason why exception occurs.
In this case try to use JSnapshot (http://jsnapshot.com).
JSnapshot is an advanced java exception logging, monitoring and analysis tool. It traces thrown exceptions in real-time and logs a snapshot of call stack, variables and objects for every thrown exception. With this tool, you can examine all of the exception details as if the application was stopped at the breakpoint in the debugger when exception happened. And it's integrated with Eclipse IDE.

Anna said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Course in Chennai

Java Online Training India

eMexoT said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

Internet Of Things training in electronic city