Sunday, 5 October 2014

Getting the Stacktrace

Found this snippet to get the stacktrace as a printable String on StackOverflow[1].
public String stackTraceToString(Throwable e)
{
StringBuilder sb = new StringBuilder();
for (StackTraceElement element : e.getStackTrace())
{
sb.append(element.toString());
sb.append("\n");
}
return sb.toString();
}
view raw StackTrace.java hosted with ❤ by GitHub
However, this only provides the stacktrace of the exception, not the possible underlying exception as well.
For that, you should look at:
public String stackTraceToString(Throwable e)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
Of course, if you do not wish to reinvent the wheel, there is always org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable).

Just thought I'd write this down here, I always forget how to do it.

References

[1] How can I convert a stack trace to a string?
http://stackoverflow.com/questions/1149703/how-can-i-convert-a-stack-trace-to-a-string

No comments:

Post a Comment