When dealing with exceptions in Java, we're frequently logging or simply displaying stack traces. However, sometimes, we don't want just to print the stack trace, we might need to write the stack trace to a file, to a database or even transmit it over the network.
For these purposes, having the stack trace as a String would be very useful. And unfortunately, Java doesn't provide a very convenient method to do that directly.
2. Conversion with Core Java
Let's start with the core library.
The function printStackTrace() of the Exception class can take one parameter, either a PrintStream or a PrintWriter. Thus, it is possible, using a StringWriter, to print the stack trace into a String:
StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw);
Then, calling sw.toString() will return the stack trace as a String.
3. Conversion with Commons-Lang
While the previous method is the simplest way of converting a stack trace to a String using core Java, it remains a bit cumbersome. Fortunately, Apache Commons-Lang provides a function doing the job.
Apache Commons-Lang is a very useful library offering a lot of features that are missing in the core classes of the Java API, including classes that can be used to work with the exceptions.
First, let's start with the project configuration. When using Maven, we just have to add the following dependency to the pom.xml:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
Then, in our case, the most interesting class is ExceptionUtils, which provides functions to manipulate the exceptions. Using this class, getting the stack trace as a String from an Exception is pretty straightforward:
String stacktrace = ExceptionUtils.getStackTrace(e);
Getting the stack trace of an exception as a String isn't difficult, but it's far from being intuitive. This article presents two ways of doing it, either using core Java or using Apache Commons-Lang.
Keep in mind that Java 9 will bring a new StackWalking API which should make things easier.
As always, the code samples can be found here on GitHub.