Java Program to Convert a Stack Trace to a String

In this program, you’ll learn to convert a stack trace to a string in Java.

Example: Convert stack trace to a string

  1. import java.io.PrintWriter;
  2. import java.io.StringWriter;
  3. public class PrintStackTrace {
  4. public static void main(String[] args) {
  5. try {
  6. int division = 0 / 0;
  7. } catch (ArithmeticException e) {
  8. StringWriter sw = new StringWriter();
  9. e.printStackTrace(new PrintWriter(sw));
  10. String exceptionAsString = sw.toString();
  11. System.out.println(exceptionAsString);
  12. }
  13. }
  14. }

When you run the program, the output will be something similar:

java.lang.ArithmeticException: / by zero
    at PrintStackTrace.main(PrintStackTrace.java:9)

In the above program, we’ve forced our program to throw ArithmeticException by dividing 0 by 0.

In the catch block, we use StringWriter and PrintWriter to print any given output to a string. We then print the stack trace using printStackTrace() method of the exception and write it in the writer.

Then, we simply convert it to string using toString() method.