HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Java StackTrace to String Example

By Lokesh Gupta | Filed Under: Java String class

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 !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Leave a Reply

This comment form is under antispam protection
This comment form is under antispam protection
  Subscribe  
Notify of

Search Tutorials

String methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

String examples

  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • String – Alignment
  • String – Immutable
  • String – StringJoiner
  • Java – Split string
  • String – Escape HTML
  • String – Unescape HTML
  • String – Convert to title case
  • String – Find duplicate words
  • String – Left pad a string
  • String – Right pad a string
  • String – Reverse recursively
  • String – Leading whitespaces
  • String – Trailing whitespaces
  • String – Remove whitespaces
  • String – Reverse words
  • String – Find duplicate characters
  • String – Check empty string
  • String – Get first 4 characters
  • String – Get last 4 characters
  • String – (123) 456-6789 pattern
  • String – Interview Questions

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz