English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java topics

Java program converts stack trace to string

Java Examples Comprehensive

In this program, you will learn how to convert stack trace to string in Java.

Example: Convert stack trace to 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);
        }
    }
}

When you run the program, the output will be similar to the following content:

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

In the above program, we force the program to throw an ArithmeticException by dividing 0 by 0

In the catch block, we use StringWriter and PrintWriter to print any given output as a string. Then we use the exception's printStackTrace() method to print the stack trace and write it to the writer

Then, we just need to use the toString() method to convert it to a string.

Java Examples Comprehensive