public class ThrowableUtil
{
public static Throwable getDeepestCause(final Throwable throwable) {
int count;
Throwable cause;
for (count = 5, cause = throwable; cause.getCause() != null && count > 0; cause = cause.getCause(), --count) {}
return cause;
}
public static String getStackPrint(final Throwable throwable) {
if (throwable == null) {
return null;
}
final Throwable cause = getDeepestCause(throwable);
final StringBuilder sb = new StringBuilder(cause.getClass().getName());
sb.append(":");
sb.append(cause.getMessage());
sb.append("\n");
final StackTraceElement[] stackArray = cause.getStackTrace();
for (int i = 0; i < stackArray.length; ++i) {
final StackTraceElement element = stackArray[i];
sb.append("\t");
sb.append(element.toString());
sb.append("\n");
}
return sb.toString();
}
public static void main(final String[] args) {
try {
try {
throw new RuntimeException("throw it ....");
}
catch (Throwable e) {
final String msg = getStackPrint(e);
throw e;
}
}
catch (Throwable e) {
getStackPrint(e);
}
}
}