Monday, December 01, 2008

Getting complete Java exception stack trace

JDK Throwable.printStackTrace() function attempts to compact the stack trace of an exception by eliminating common parents of all stack elements. However it is often helpful to see the entire stack trace.

E.g. if using JDK you may write this function to get the stack trace of an exception as a String:

public static String formatStackTrace(Throwable e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
return stringWriter.toString();
}


To obtain the complete stack trace you may use this function:

private static String formatStackTrace(Throwable e) {
StringBuffer str = new StringBuffer();
str.append(e.getClass().getName()).append(": ");
str.append(e.getMessage());
StackTraceElement[] stack = e.getStackTrace();
for (int i = 0; i < stack.length; i++) {
StackTraceElement element = stack[i];
str.append("\n\tat ").append(element.getClassName()).
append(".").append(element.getMethodName()).
append("(").append(element.getFileName()).append(":").
append(element.getLineNumber()).append(")");
}

Throwable cause = e.getCause();
if (cause != null) {
str.append("\nCaused by: ").append(formatStackTrace(cause));
}
return str.toString();
}

No comments: