Thursday, June 11, 2026
HomeLanguagesJavaJava Program to Convert a Stack Trace to a String

Java Program to Convert a Stack Trace to a String

Prerequisite knowledge of the following Java programming topics:

Convert Stack Trace to String

In the program below, we’ve dropped an ArrayIndexOutOfBoundsException to our program by accessing an out-of-bounds element. The Java StringWriter class is a character stream that collects the output from the string buffer that can be used to construct strings. The Java PrintWriter class is a part of the java.io package which is used to write output data in the form of text. Using StringWriter and PrintWriter in the catch block, and the purpose behind it is to print the given output in the form of a string.

Now print the stack trace using the printStackTrace() method of the exception and after that write it in the writer. And finally, convert it into a string using the toString() method.

 

Implementation:

Java




// Java Program to convert a Stack trace to a string
  
import java.io.*;
  
public class PrintStackTrace {
  
    public static void main(String[] args)
    {
  
        try {
            int a[] = new int[3];
            System.out.println(
                "Printing element at index four:" + a[4]);
        }
        catch (ArrayIndexOutOfBoundsException e) {
            StringWriter string_writer = new StringWriter();
            e.printStackTrace(
                new PrintWriter(string_writer));
  
            String printExceptionAsString
                = string_writer.toString();
            System.out.println(printExceptionAsString);
        }
    }
}


Output

java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3
    at PrintStackTrace.main(PrintStackTrace.java:12)

RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6896 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS