10

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
2
  • 1
    It's probably worth noting that the printStackTrace method 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 any StackTraceElement from the cause that is common to the original exception, hence the phrase ... <int> more Commented Feb 22, 2012 at 22:49
  • excellent point. That is another reason that I want more elegant way to do it. Commented Feb 23, 2012 at 13:44

2 Answers 2

24

There is:

StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String stackTrace = writer.toString();
answered Feb 22, 2012 at 22:31
Sign up to request clarification or add additional context in comments.

Comments

4

using commons-lang :

String stackTrace = ExceptionUtils.getStacktrace(e);

javadoc : ExceptionUtils.html#getStackTrace().

answered Feb 22, 2012 at 22:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.