Dec 21

Sometimes you need to store the stack trace from an exception in a String. A common approach is to use the printStackTrace() method to write it to a String which gives it to you in the same format as when you print it to stdout (or whereever)

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String trace = sw.toString();

Another option is to use the stack trace directly to create your string. This allows you to have full control over the format. For example you could use something as simple as the following:

String trace = Arrays.toString(ex.getStackTrace());

written by objects \\ tags: , , , ,


One Response to “How to store exception stack trace as String”

  1. Sanjay Biswal Says:

    Good Question Answer.

Leave a Reply

You must be logged in to post a comment.