Java - Writing Stack Trace of an Exception to a String

Description

Writing Stack Trace of an Exception to a String

Demo

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

public class Main {
  public static void main(String[] args) {
    try {//from ww w  .j av a 2s  .  co m
      m1();
    } catch (MyException e) {
      String str = getStackTrace(e);

      // Print the stack trace to the standard output
      System.out.println(str);
    }
  }

  public static void m1() throws MyException {
    m2();
  }

  public static void m2() throws MyException {
    throw new MyException("Some error has occurred.");
  }

  public static String getStackTrace(Throwable e) {
    StringWriter strWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(strWriter);
    e.printStackTrace(printWriter);

    // Get the stack trace as a string
    String str = strWriter.toString();

    return str;
  }
}

class MyException extends Exception {

  public MyException() {
    super();
  }

  public MyException(String message) {
    super(message);
  }

  public MyException(String message, Throwable cause) {
    super(message, cause);
  }

  public MyException(Throwable cause) {
    super(cause);
  }
}

Result

Related Topic