How can I convert a stack trace to a string?

前端 未结 30 1156
再見小時候
再見小時候 2020-11-22 14:51

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

30条回答
  •  囚心锁ツ
    2020-11-22 15:24

    Code from Apache Commons Lang 3.4 (JavaDoc):

    public static String getStackTrace(final Throwable throwable) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        throwable.printStackTrace(pw);
        return sw.getBuffer().toString();
    }
    

    The difference with the other answers is that it uses autoFlush on the PrintWriter.

提交回复
热议问题