How can I convert a stack trace to a string?

前端 未结 30 1453
再見小時候
再見小時候 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:19

    Use Throwable.printStackTrace(PrintWriter pw) to send the stack trace to an appropriate writer.

    import java.io.StringWriter;
    import java.io.PrintWriter;
    
    // ...
    
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    String sStackTrace = sw.toString(); // stack trace as a string
    System.out.println(sStackTrace);
    

提交回复
热议问题