How do I capture an exception stack trace and put it into a string?

Luigi Viggiano

Here's how to print the trace in a string:

Exception ex = new Exception("something went wrong");
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
System.out.println("stacktrace = " + stacktrace);
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.