Java StackTrace to String Example

Java program to convert error stack trace to String. StackTrace to String conversion may be useful when you want to print stack trace in custom logs in files or store logs in database.

1. StackTrace to String with ExceptionUtils

Apache common langs library has one excellent utility class ExceptionUtils. It’s getStackTrace() method returns string representation of any Java exception.

1.1. Maven

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

1.2. Java program to convert stack trace to string

This example copy the stack trace to 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)

2. StackTrace to String with StringWriter

To convert printStackTrace() to string, follow these steps –

  1. Print throwable stack trace and its backtrace to the PrintWriter.
  2. Copy print writer content to StringWriter.
  3. Use StringWriter.toString() to get stack trace in string format.

I ma using try-with-resource feature to create StringWriter and PrintWriter instances. It helps in getting AutoCloseable streams from both writers.

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

public class StringExample 
{
	public static void main(String[] args) 
	{
		String error  = convertStackTraceToString(new NullPointerException("Custom error"));
		
		System.out.println(error);
	}
	
	private static String convertStackTraceToString(Throwable throwable) 
	{
	    try (StringWriter sw = new StringWriter(); 
	           PrintWriter pw = new PrintWriter(sw)) 
	    {
	        throwable.printStackTrace(pw);
	        return sw.toString();
	    } 
	    catch (IOException ioe) 
	    {
	        throw new IllegalStateException(ioe);
	    }
	}   
}

Program output.

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

In the above program, we’ve created a NullPointerException and printed its stack trace in console after converting to String.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.