Java 101Converting Stacktrace to String

time to read 1 min | 70 words

To store stack trace as a string, you can use Throwable.printStackTrace(...) For example:

public static String getStackTrace(
  Throwable throwable
  Writer result = new StringWriter();
  PrintWriter printWriter = 
    new PrintWriter(result);
  return result.toString();

In the above example, getStackTrace takes a Throwable as a parameter and uses printStackTrace to print it to a PrintWriter output stream. This output is collected by the StringWriter and converted to a string using StringWriter.toString().