What is the easiest way to convert the result of Throwable.getStackTrace()
to a string that depicts the stacktrace?
How can I convert a stack trace to a string?
2021-6-3 anglehua
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)
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);
采集自互联网,如有侵权请联系本人