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);
e.printStackTrace(pw);
retValue = sw.toString();
} finally {
try {
if(pw != null) pw.close();
if(sw != null) sw.close();
} catch (IOException ignore) {}
}
return retValue;
}

Followers

Pageviews Last 7 Days