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);
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: , , , ,