retrieve the full stacktrace from a given exception - Java java.lang

Java examples for java.lang:Exception

Description

retrieve the full stacktrace from a given exception

Demo Code

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Vector;

public class Main{

    /**//from  ww w.  j a  va2 s. c om
     * Convenient method to retrieve the full stacktrace from a given exception.
     *
     * @param t
     *            the exception to get the stacktrace from.
     * @return the stacktrace from the given exception.
     */
    public static String getStackTrace(Throwable t) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw, true);
            t.printStackTrace(pw);
            pw.flush();
            pw.close();
            return sw.toString();
        } finally {
            sw = null;
            pw = null;
        }
    }

}

Related Tutorials