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 Find the Shortest Path Between Two Vertices Using Dijkstra’s Algorithm
Guide to java.util.Formatter
Hướng dẫn tạo và sử dụng ThreadPool trong Java
Java Program to Implement K Way Merge Algorithm
Java – Write a Reader to File
Spring 5 Functional Bean Registration
The HttpMediaTypeNotAcceptableException in Spring MVC
Java Program to Check Whether Graph is DAG
Java Program to Implement Extended Euclid Algorithm
Java Program to Check if it is a Sparse Matrix
Convert String to int or Integer in Java
Interface trong Java 8 – Default method và Static method
Java Program to Construct an Expression Tree for an Prefix Expression
XML-Based Injection in Spring
Java Program to Find All Pairs Shortest Path
Java Program to Perform String Matching Using String Library
Check if there is mail waiting
Concatenating Strings In Java
Java Program to Implement wheel Sieve to Generate Prime Numbers Between Given Range
Shuffling Collections In Java
Java Program to Implement Hamiltonian Cycle Algorithm
Tips for dealing with HTTP-related problems
Hướng dẫn Java Design Pattern – Strategy
Java Program to Implement Solovay Strassen Primality Test Algorithm
String Initialization in Java
Introduction to the Functional Web Framework in Spring 5
Constructor Injection in Spring with Lombok
Java Program to Implement Borwein Algorithm
Java Program to Create a Minimal Set of All Edges Whose Addition will Convert it to a Strongly Conne...
HTTP Authentification and CGI/Servlet
Quick Guide to the Java StringTokenizer
Java Program to Perform Stooge Sort