Join our newsletter for the latest updates.

Java Program to Convert a Stack Trace to a String

In this program, you'll learn to convert a stack trace to a string in Java.

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Convert stack trace to a string

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

public class PrintStackTrace {

    public static void main(String[] args) {

        try {
            int division = 0 / 0;
        } catch (ArithmeticException e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            System.out.println(exceptionAsString);
        }
    }
}

Output

java.lang.ArithmeticException: / by zero
    at PrintStackTrace.main(PrintStackTrace.java:9)

In the above program, we've forced our program to throw ArithmeticException by dividing 0 by 0.

In the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using printStackTrace() method of the exception and write it in the writer.

Then, we simply convert it to string using toString() method.

Did you find this article helpful?