Alex Rivera | Logout

How can I convert a stack trace to a string?

Asked 2009-07-19T11:31:43.533
1753

What is the easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?

Edit
Report

2 Answers

120

WARNING: Does not include cause (which is usually the useful bit!)

public String stackTraceToString(Throwable e) {
    StringBuilder sb = new StringBuilder();
    for (StackTraceElement element : e.getStackTrace()) {
        sb.append(element.toString());
        sb.append("\n");
    }
    return sb.toString();
}
answered 2009-07-19T11:38:56.560
27

The following code allows you to get the entire stackTrace with a String format, without using APIs like log4J or even java.util.Logger:

catch (Exception e) {
    StackTraceElement[] stack = e.getStackTrace();
    String exception = "";
    for (StackTraceElement s : stack) {
        exception = exception + s.toString() + "\n\t\t";
    }
    System.out.println(exception);
    // then you can send the exception string to a external file.
}
answered 2012-10-24T16:57:43.100

Your Answer