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();
}

4 comments:

Jackie Gleason said...

I tried to use this on a exception stack trace

String x = getStackTrace(e.printStackTrace);

And I get a compilation error any ideas? Am I using it wrong?

Jackie Gleason said...

er Sorry

String x = getStackTrace(e.printStackTrace());

And the error is incompatable type void type not allowed

Jackie G. 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.