Java Program to Convert a Stack Trace to a String

In the following example of Java program to convert a stack trace to a string :
Program :
import java.io.PrintWriter;
import java.io.StringWriter;

public class StackTraceToString {
    public static void main(String[] args) {
        try {
            throw new Exception("Test exception");
        } catch (Exception e) {
            String stackTraceString = getStackTraceString(e);
            System.out.println(stackTraceString);
        }
    }
    
    public static String getStackTraceString(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        return sw.toString();
    }
}
Output :
java.lang.Exception: Test exception
	at StackTraceToString.main(StackTraceToString.java:7)
In this program, we intentionally throw an exception and catch it in a try-catch block. We then call the getStackTraceString() method, passing the caught exception as input. This method converts the stack trace of the exception to a string using a StringWriter and a PrintWriter, and returns the resulting string.

The getStackTraceString() method takes a Throwable object as input, which can be any object that represents an exception or error. It creates a new StringWriter and a new PrintWriter, passing the StringWriter as the output destination for the PrintWriter. It then calls the printStackTrace() method of the Throwable object, passing the PrintWriter as the output destination. This causes the stack trace of the Throwable object to be written to the StringWriter. Finally, it returns the string that was written to the StringWriter.