Java – print stack trace to a String

Simple and quick one today – what if we need to print stack trace into a String?

[java]

catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();

String stackTraceString = sw.toString();
//use the stackTraceString as you need…
}

[/java]

Comments are closed.