Open In App

Java Program to Convert a Stack Trace to a String

Improve
Improve
Like Article
Like
Save
Share
Report

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)


Last Updated : 08 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads