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.

Example: Convert stack trace to a string


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();


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

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.

Leave a Reply