Easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?
+22
A:
Use Throwable.printStackTrace(PrintWriter pw) to send the stack trace to an appropriate writer.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
sw.toString(); // stack trace as a string
Brian Agnew
2009-07-19 11:36:22
+6
A:
public String stackTraceToString(Throwable e) {
StringBuilder sb = new StringBuilder();
for (StackTraceElement element : e.getStackTrace) {
sb.append(element.toString());
sb.append("\n");
}
return sb.toString();
}
jqno
2009-07-19 11:38:56
This is good if you just want the stack trace (as the OP asks)
Peter Lawrey
2009-07-19 11:48:58
I'd go with an extension of this approach if you want to trim the trace, e.g. pass a maxLines parameter and only add that many lines to the trace
Rich Seller
2009-07-19 12:28:36
+8
A:
This should work:
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsStrting = sw.toString();
D. Wroblewski
2009-07-19 11:41:22
+7
A:
Even one can use the following method to convert exception stack trace to string. This class is available in apache commons-lang-2.2.jar
org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)
amar
2010-01-21 14:39:54
javadoc: http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/exception/ExceptionUtils.html#getStackTrace(java.lang.Throwable)
askullhead
2010-07-07 14:36:04