Convert a Stack Trace to a String in Java

Exercise:

Write a Java Program to convert a stack trace to a string.

Click Here to View the Solution!
import java.io.StringWriter;
public class StackTrace {
  
     public static void main(String[] args) {
    try {
             int division = 0 / 0;
         } catch (ArithmeticException e) {
             StringWriter sw = new StringWriter();
             e.printStackTrace(new PrintWriter(sw));
             String exceptionAsString = sw.toString();
             System.out.println(exceptionAsString);
         }
     }
 } 
Click Here to View the Output!
java.lang.ArithmeticException: / by zero
     at Main.main(Main.java:16)
Click Here to View the Explanation!
  • In this program, for the purpose of demonstrating the exception handling, 0 has been dividing by 0 which will throw an ArithmeticException.
  • PrintWriter and StringWriter have been utilized in the catch block after encountering an exception. These are used for the purpose of displaying output in the form of a string.
  • Stack trace is printed by using an Exception method called printStackTrace() and it is then written in the writer.
  • Finally, the conversion takes place after which we have a string by utilizing the toString() method.