Writing Stack Trace of an Exception to a String - Java Object Oriented Design

Java examples for Object Oriented Design:Exception

Description

Writing Stack Trace of an Exception to a String

Demo Code

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

public class Main {
  public static void main(String[] args) {
    try {/*ww w .j a  va  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);
  }
}

Related Tutorials