如何从Java中的线程传播异常? [英] How to propagate exception from thread in java?

查看:74
本文介绍了如何从Java中的线程传播异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

    outerMethod {
        @Override
        public void run() {
                innerMethod throws IOException
                }
    }

在线程中执行的方法将引发检查的异常-IOException. 我需要在主线程中处理此异常. 像:

Method that exceuted in thread throws checked exception - IOException. I need to handle this exception in main thread. Like:

outerMethod() throws IOException
   {
        @Override
        public void run() {
                innerMethod() throws IOException
                }
    }

这可能吗?如果没有,哪种更好的方法呢?

Is this possible? If no, what would be a better way to do this?

谢谢.

推荐答案

使用FutureTask

Use FutureTask http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/FutureTask.html#get%28%29 . It's get methods will encapsulate any exceptions from the task that might have run on another thread.

ExecutionException:尝试检索因引发异常而中止的任务的结果时引发的异常.可以使用Throwable.getCause()方法检查此异常.

ExecutionException: Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the Throwable.getCause() method.

这篇关于如何从Java中的线程传播异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆