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 –
- Print throwable stack trace and its backtrace to the PrintWriter.
- Copy print writer content to StringWriter.
- 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 !!
Leave a Reply