Thursday, August 24, 2006

Convert exception stacktrace to String object


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 t’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();

return stringWritter.toString();
}

2 comments:

J. Gleason said...

Nm got it just needed to use the exception as a param didn't really get that at first Thanks

Jaikiran said...

Yes you are right. You need to pass the exception object to the method. Earlier you were passing a void since exception.printStackTrace() returns void.