Java Convert Exception StackTrace as String

Remember that exception.printStackTrace() method that outputs detailed messages about the error in the console? That method returns void so there’s no way to get those messages stored in a String. Try this handy method does the trick. Just pass the exception object as the parameter for this method.


import java.io.PrintWriter;
import java.io.StringWriter;

public static String getExceptionStackTraceAsString(Exception exception) {
  StringWriter sw = new StringWriter();
  exception.printStackTrace(new PrintWriter(sw));
  return sw.toString();
}

Found this useful? Donations appreciated to help keep this blog alive.

Related Posts Plugin for WordPress, Blogger...
  1. 2 Responses to “Java Convert Exception StackTrace as String”

  2. Very useful content in there.. Well done..

    By herc on Nov 19, 2009

  3. Thankyou so much

    By Muthu on Nov 5, 2011

Post a Comment