Java Throwable to String getStackTrace(Throwable t)

Here you can find the source of getStackTrace(Throwable t)

Description

Gets the stack trace of the given Throwable as a String.

License

Open Source License

Parameter

Parameter Description
t the throwable object for which to get the stack trace

Return

the stack trace of the given Throwable

Declaration

public static String getStackTrace(Throwable t) 

Method Source Code

//package com.java2s;

import java.io.PrintWriter;

import java.io.StringWriter;

public class Main {
    /** Gets the stack trace of the given Throwable as a String.
    * @param t the throwable object for which to get the stack trace
    * @return the stack trace of the given Throwable
    *//* w  w w .j av a  2  s .co  m*/
    public static String getStackTrace(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        return sw.toString();
    }

    /** Gets the stack trace of the current code. Does not include this method.
      * @return the stack trace for the current code
      */
    public static String getStackTrace() {
        // TODO: Thread.getStackTrace() which is new to Java 5.0 might be more efficient
        try {
            throw new Exception();
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            StackTraceElement[] stes = e.getStackTrace();
            int skip = 1;
            for (StackTraceElement ste : stes) {
                if (skip > 0)
                    --skip;
                else {
                    pw.print("at ");
                    pw.println(ste);
                }
            }
            return sw.toString();
        }
    }
}

Related

  1. getStackTrace(Throwable t)
  2. getStackTrace(Throwable t)
  3. GetStacktrace(Throwable t)
  4. getStackTrace(Throwable t)
  5. getStackTrace(Throwable t)
  6. getStackTrace(Throwable t)
  7. getStackTrace(Throwable t)
  8. getStackTrace(Throwable t)
  9. getStackTrace(Throwable t)