Usually whenever a exception occurs, we use the method printStackTrace() on the exception object to display the stacktrace. However, if the stacktrace has to be stored into a String object then the following piece of code will prove handy:
/**
* Creates and returns a {@link java.lang.String} from <code>t</code>’s stacktrace
* @param t Throwable whose stack trace is required
* @return String representing the stack trace of the exception
*/
public String getStackTrace(Throwable t) {
StringWriter stringWritter = new StringWriter();
PrintWriter printWritter = new PrintWriter(stringWritter, true);
t.printStackTrace(printWritter);
printWritter.flush();
stringWritter.flush();