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?
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