How can I convert a stack trace to a string?

2018-12-31 19:17发布

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

28条回答
情到深处是孤独
2楼-- · 2018-12-31 20:09

One can use the following method to convert an Exception stack trace to String. This class is available in Apache commons-lang which is most common dependent library with many popular open sources

org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)

查看更多
还给你的自由
3楼-- · 2018-12-31 20:11

Use exp.printStackTrace() for displaying stack of your exception.

try {
   int zero = 1 - 1;
   int a = 1/zero;
} catch (Exception e) {
    e.printStackTrace();
}
查看更多
长期被迫恋爱
4楼-- · 2018-12-31 20:12
private String getCurrentStackTraceString() {
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    return Arrays.stream(stackTrace).map(StackTraceElement::toString)
            .collect(Collectors.joining("\n"));
}
查看更多
千与千寻千般痛.
5楼-- · 2018-12-31 20:13

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();
}
查看更多
登录 后发表回答