Java Program to Convert a Stack Trace to a String


The Java.io.StringWriter class is a character stream that collects its output in a string buffer, which can then be used to construct a string. Closing a StringWriter has no effect.

The Java.io.PrintWriter class prints formatted representations of objects to a text-output stream.

Using these two classes you can convert a Stack Trace to a String.

Example

Live Demo

import java.io.PrintWriter;
import java.io.StringWriter;

public class StackTraceToString {
   public static void main(String args[]) {
      try {
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      } catch (ArrayIndexOutOfBoundsException e) {
         StringWriter writer = new StringWriter();
         e.printStackTrace(new PrintWriter(writer));

         String myString = writer.toString();
         System.out.println("Stack trace message ::"+myString);
      }
   }
}

Output

Stack trace message ::java.lang.ArrayIndexOutOfBoundsException: 3
   at lastRound.StackTraceToString.main(StackTraceToString.java:10)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 13-Mar-2020

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements