ThrowableUtil

本文介绍了一个Java工具类,用于获取异常的根本原因及堆栈跟踪信息。该工具类提供了两个主要方法:getDeepestCause用于查找异常链中最深层的原因;getStackPrint则返回异常的详细信息,包括类名、消息及堆栈跟踪。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
        }
    }
}

 

转载于:https://www.cnblogs.com/tonggc1668/p/7097379.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值