ThrowableUtil

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("
");
        final StackTraceElement[] stackArray = cause.getStackTrace();
        for (int i = 0; i < stackArray.length; ++i) {
            final StackTraceElement element = stackArray[i];
            sb.append("	");
            sb.append(element.toString());
            sb.append("
");
        }
        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);
        }
    }
}
原文地址:https://www.cnblogs.com/tonggc1668/p/7097379.html