You can use the getStackTrace() method to get an array of StackTraceElements, and generate a String from there. Otherwise, if just the final error message is sufficient, use the getMessage()
method as suggested by Makoto.
To get the stack trace as a String
from an array of StackTraceElement
objects, you need to iterate over the array (taken from JDK7 source):
StringBuilder builder = new StringBuilder();
StackTraceElement[] trace = getOurStackTrace();
for (StackTraceElement traceElement : trace)
builder.append("\tat " + traceElement + "\n");
Another option is to use printStackTrace(PrintStream s)
, where you get to specify where you want the stacktrace to be printed:
ByteArrayOutputStream out1 = new ByteArrayOutputStream();
PrintStream out2 = new PrintStream(out1);
ex.printStackTrace(out2);
String message = out1.toString("UTF8");