Print the stack trace of an exception

Solution 1:

Not beautiful, but a solution nonetheless:

StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter( writer );
exception.printStackTrace( printWriter );
printWriter.flush();

String stackTrace = writer.toString();

Solution 2:

There is an alternate form of Throwable.printStackTrace() that takes a print stream as an argument. http://download.oracle.com/javase/6/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)

E.g.

catch(Exception e) {
    e.printStackTrace(System.out);
}

This will print the stack trace to std out instead of std error.

Solution 3:

Throwable.printStackTrace(..) can take a PrintWriter or PrintStream argument:

} catch (Exception ex) {
    ex.printStackTrace(new java.io.PrintStream(yourOutputStream));
}

That said, consider using a logger interface like SLF4J with an logging implementation like LOGBack or log4j.

Solution 4:

For the android dev minimalists: Log.getStackTraceString(exception)