Java Program to Convert a Stack Trace to a String

Object Oriented ProgrammingJava8Java Programming

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)
raja
Published on 26-Apr-2018 16:16:48
Advertisements