java怎么捕获error_java-如何从执行程序中正确捕获RuntimeException?

提交给ThreadPoolExecutors的任务(callable或Runnable)将转换为FuturnTask,其中包含名为callable的道具,它等于您提交的任务。 FuturnTask具有其自己的run方法,如下所示。 将捕获c.call()中抛出的所有异常或可投掷,并将其放入名为outcome的道具中。调用FuturnTask的get方法时,将抛出outcome

来自Jdk1.8的FuturnTask.run源代码

public void run() {

...

try {

Callable c = callable;

if (c != null && state == NEW) {

V result;

boolean ran;

try {

result = c.call();

ran = true;

} catch (Throwable ex) {

result = null;

ran = false;

// save ex into `outcome` prop

setException(ex);

}

if (ran)

set(result);

}

}

...

}

如果您想捕获异常:

1.斯卡夫曼的答案

2.新建ThreadPoolExecutor时覆盖`afterExecute`

@Override

protected void afterExecute(Runnable r, Throwable t) {

super.afterExecute(r, t);

Throwable cause = null;

if (t == null && r instanceof Future) {

try {

((Future>) r).get();

} catch (InterruptedException | ExecutionException e) {

cause = e;

}

} else if (t != null) {

cause = t;

}

if (cause != null) {

// log error

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值