简体   繁体   English

如何在java中传播线程中的异常?

[英]How to propagate exception from thread in java?

Code: 码:

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

Method that exceuted in thread throws checked exception - IOException. 在线程中抛出的方法抛出已检查的异常 - 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? 如果不是,那么更好的方法是什么?

Thanks. 谢谢。

Use FutureTask http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/FutureTask.html#get%28%29 . 使用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. 它的get方法将封装可能在另一个线程上运行的任务的任何异常。

ExecutionException: Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. ExecutionException:尝试检索通过抛出异常而中止的任务的结果时抛出异常。 This exception can be inspected using the Throwable.getCause() method. 可以使用Throwable.getCause()方法检查此异常。

Thread is an individual process and you cannot propagate your exception to other thread as they cannot talk through the exception route. 线程是一个单独的进程,您无法将异常传播到其他线程,因为它们无法通过异常路由进行通信。 However you can use inter thread communication and you will have to logically handle the case when an exception occurs. 但是,您可以使用线程间通信,并且必须在发生异常时以逻辑方式处理该情况。

From this API doc 这个API文档

If thread has defined UncaughtExceptionHandler, it will be invoked, Else thread group's UncaughtExceptionHandler will be invoked if defined, Else it can forward to default uncaught exception handler. 如果线程已定义UncaughtExceptionHandler,则将调用它,如果已定义则将调用Else线程组的UncaughtExceptionHandler,否则它可以转发到默认的未捕获异常处理程序。

You have to handle exceptions inside run method : 您必须在run方法中处理异常:

        @Override
        public void run() {
           try {
              innerMethod();
           } catch (Exception e) {
             //handle e
           }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM