Skip to content
Related Articles

Related Articles

Improve Article
Java Program to Convert a Stack Trace to a String
  • Difficulty Level : Medium
  • Last Updated : 08 Dec, 2020

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)

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :