I need to log a stack trace when I catch an exception in my Java app. I know that exceptions have a built in printStackTrace() method, and that that can send the stack trace to a different PrintWriter/PrintStream, but it would be useful if I could grab the stack trace as a String so that I can manipulate it or display it in a JMessagePane or something. Currently, the only way I have to do this is:
String stackTrace = "";
stackTrace += e.getClass().getName() + ": " + e.getMessage() + "\n";
for (StackTraceElement elt : e.getStackTrace()) {
stackTrace += "\tat " + elt + "\n";
}
Is there a cleaner way to do this?
asked Feb 22, 2012 at 22:25
ewok
21.7k56 gold badges165 silver badges267 bronze badges
2 Answers 2
There is:
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String stackTrace = writer.toString();
answered Feb 22, 2012 at 22:31
Tomasz Nurkiewicz
342k72 gold badges713 silver badges680 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
using commons-lang :
String stackTrace = ExceptionUtils.getStacktrace(e);
javadoc : ExceptionUtils.html#getStackTrace().
answered Feb 22, 2012 at 22:38
Sébastien Helbert
2,20014 silver badges24 bronze badges
Comments
lang-java
printStackTracemethod does much more than the alternative suggested in the question body. That is, it includes the stacktrace for the cause if one is set and excludes anyStackTraceElementfrom the cause that is common to the original exception, hence the phrase... <int> more