Converting a Stack Trace to a String in Java

1. Introduction

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.11</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);

4. Conclusion

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.

Related posts:

Java Program to Implement Floyd Cycle Algorithm
Java Program to Perform Cryptography Using Transposition Technique
Jackson – Unmarshall to Collection/Array
Converting Between an Array and a Set in Java
Java Program to Perform the Sorting Using Counting Sort
Removing Elements from Java Collections
Java Program to Evaluate an Expression using Stacks
Java Program to Implement Leftist Heap
Sử dụng CyclicBarrier trong Java
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Python Program to Check Whether a String is Palindrome or Not
Encode a String to UTF-8 in Java
Java Program to Check the Connectivity of Graph Using BFS
Java Program to Implement Rope
Java – Byte Array to Reader
Java Program to Implement Shunting Yard Algorithm
Consuming RESTful Web Services
Java Program to Encode a Message Using Playfair Cipher
LinkedHashSet trong Java hoạt động như thế nào?
Python String translate()
Spring Boot - Interceptor
An Introduction to Java.util.Hashtable Class
Assertions in JUnit 4 and JUnit 5
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Multi Dimensional ArrayList in Java
Generating Random Dates in Java
Java Program to Implement Segment Tree
Java Program to Implement vector
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers