Skip to content
Related Articles

Related Articles

Java Program to Convert a Stack Trace to a String

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 08 Dec, 2020
Improve Article
Save Article

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 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.




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


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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!