views:

1979

answers:

4

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
+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
This is good if you just want the stack trace (as the OP asks)
Peter Lawrey
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
+8  A: 

This should work:

StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsStrting = sw.toString();
D. Wroblewski
+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
javadoc: http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/exception/ExceptionUtils.html#getStackTrace(java.lang.Throwable)
askullhead