Place Stack Trace into a String in Java

Java 8Object Oriented ProgrammingProgramming

In order to place stack trace into a String in Java, we use the java.io.StringWriter and java.io.PrintWriter classes. In a catch block, after catching the exception, we print the stack trace by printStackTrace() method and write it into the writer and then use the ToString() method to convert it into a String.

Let us see a program to place the stack trace into a String in Java.

Example

 Live Demo

import java.io.PrintWriter;
import java.io.StringWriter;
public class Example {
   public static void main(String[] args) {
      try{
         int ans = 10/0;
      }catch (ArithmeticException ex) {
         StringWriter s= new StringWriter();
         ex.printStackTrace(new PrintWriter(s)); // writing the stack trace in the writer
         String str = s.toString(); // converting it into a String
         System.out.println(str);
      }
   }
}

Output

java.lang.ArithmeticException: / by zero
at Example.main(Example.java:8)
raja
Published on 04-Jan-2019 06:26:44
Advertisements