Convert Exception StackTrace to String in Java

Learn to convert Java exception stack trace to a String. From StackTrace to String conversion may be useful when we want to print stack traces in log files or store logs in a database for audit purposes.

Note that Java does not have an inbuilt direct API to get the stack trace as String.

1. Using StringWriter and PrintWriter

By default, Throwable.printStackTrace() prints the exception backtrace to the standard error stream that is the value of the field System.err. By default, the System.err prints to the console.

We can use the overloaded method printStackTrace(writer) to print the backtrace to the specified print Writer such as a PrintWriter. This PrintWriter is targeted towards a StringWriter.

To convert a stack trace using StringWriter, follow these steps

  • Print throwable stack trace and its backtrace to the PrintWriter.
  • Copy print writer content to StringWriter.
  • Use StringWriter.toString() to get the stack trace as string.

We are using try-with-resource to create StringWriter and PrintWriter instances that automatically close both writers when processing is complete.

In the following program, we create a NullPointerException and print its stack trace after converting it to String.

NullPointerException npe = new NullPointerException("Custom error");
String errorStr = null;

try (StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw)) {

  npe.printStackTrace(pw);
  errorStr = sw.toString();

} catch (IOException e) {
  throw new RuntimeException("Error while converting the stacktrace");
}

System.out.println(errorStr);

Program output.

java.lang.NullPointerException: Custom error
	at com.howtodoinjava.demo.StackTrace.main(StackTrace.java:11)

2. Using ExceptionUtils

Apache common langs3 library has one excellent utility class ExceptionUtils. Its getStackTrace() method returns a string representation of any Java exception.

2.1. Maven

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

2.2. Example

The following Java program copies the stack trace to a string.

String errorStr = ExceptionUtils.getStackTrace(new NullPointerException("Custom error"));

System.out.println(errorStr);

Program output.

java.lang.NullPointerException: Custom error
	at com.howtodoinjava.demo.StringExample.main(StringExample.java:11)

Happy Learning !!

Sourcecode on Github

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial