java 线程抛出异常_java – 嵌套线程可以为父线程抛出异常吗?

How do I throw exception to the outside of the thread?

夫妻俩可以做到这一点.您可以在线程上设置UncaughtExceptionHandler,也可以使用ExecutorService.submit(Callable)并使用从Future.get()获得的异常.

最简单的方法是使用ExecutorService:

ExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();

Future future = threadPool.submit(new Callable() {

public Void call() throws Exception {

// can throw OhNoException here

return null;

}

});

// you need to shut down the pool after submitting the last task

threadPool.shutdown();

// this can throw ExecutionException

try {

// this waits for your background task to finish,it throws if the task threw

future.get();

} catch (ExecutionException e) {

// this is the exception thrown by the call() which could be a OhNoException

Throwable cause = e.getCause();

if (cause instanceof OhNoException) {

throw (OhNoException)cause;

} else if (cause instanceof RuntimeException) {

throw (RuntimeException)cause;

}

}

如果您想使用UncaughtExceptionHandler,那么您可以执行以下操作:

Thread thread = new Thread(...);

final AtomicReference throwableReference = new AtomicReference();

thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

public void uncaughtException(Thread t,Throwable e) {

throwableReference.set(e);

}

});

thread.start();

thread.join();

Throwable throwable = throwableReference.get();

if (throwable != null) {

if (throwable instanceof OhNoException) {

throw (OhNoException)throwable;

} else if (throwable instanceof RuntimeException) {

throw (RuntimeException)throwable;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值