Print the stack trace of an exception
Not beautiful, but a solution nonetheless:
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter( writer );
exception.printStackTrace( printWriter );
printWriter.flush();
String stackTrace = writer.toString();
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.
For the android dev minimalists: Log.getStackTraceString(exception)
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.