【Java异常】Throwable之getCause()

Throwable - getCause()

1 定义

the cause of this throwable or null if the cause is nonexistent or unknown.

返回引起此异常的原因或者 null (不存在原因或者未知情况)。

2 举例

public class Throwable$getCauseTest {
    public static void main(String[] args) {
        getCause1();
        getCause2();
    }

    public static void getCause1() {
        try {
            throw new RuntimeException("main error!");
        } catch (Exception e) {
            System.out.println(e.getCause() instanceof RuntimeException);
            System.out.println("e:" + e + "; e.getCause():" + e.getCause());
        }
    }

    public static void getCause2() {

        Runnable r1 = () -> {
            throw new RuntimeException("Thread error!");
        };

        Future<Integer> task = Executors.newSingleThreadExecutor().submit(r1, 1);

        try {
            task.get();
        } catch (Exception e) {
            System.out.println(e.getCause() instanceof RuntimeException);
            System.out.println("e:" + e + "; e.getCause():" + e.getCause());
        }
    }
}

// 输出结果
false
e:java.lang.RuntimeException: main error!; e.getCause():null
    
true
e:java.util.concurrent.ExecutionException: java.lang.RuntimeException: Thread error!;
e.getCause():java.lang.RuntimeException: Thread error!

3 总结

  • 例如线程池抛出的异常,最外层是 ExecutionException,所以 getCause() 能够获取到里层 RuntimeException

  • 直接捕获抛出的异常,调用 getCause() 则返回的 null




感谢阅读,下次再见。ヾ( ̄▽ ̄)ByeBye

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值