How to convert a stack trace to String

December 26, 2016

In this post, we will convert a stack trace to String. There are multiple methods for doing this.

1. Using StringWriter and PrintWriter

The first method is to use StringWriter and PrintWriter classes. Let’s have a look on a below example.

In the first line, we create an instance of the StringWriter class. After that, we create an instance of PrintWriter using previously create StringWriter. Nextly, we use the Throwable.printStackTrace(PrintWriter) method to print the Exception stack trace to the printWriter object. Lastly, we print the exception stack trace, which is now stored in stringWriter.

2. Using Apache Commons Lang – ExceptionUtils

The another method is to use the ExceptionUtils.getStackTrace(Throwable) method.

This method simply gets a stack trace from a Throwable as a String. The String’s content is exactly the same as in the example above.

3. Using Google Guava – Throwables

You can also use the Throwables.getStackTraceAsString(Throwable) method.

The variable content is now exactly the same as in the first example.

Click here to add a comment

Leave a comment: