【问题标题】:Callable and Future return exception可调用和未来返回异常
【发布时间】:2014-05-22 07:13:28
【问题描述】:

我有以下代码。

Future<Integer> future = Executor.execute(callable);
            Integer i;
            try {
                i = future.get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return MESSAGE_INT_CODE;
            } catch (ExecutionException e) {
                 // TODO Auto-generated catch block
                 //e.printStackTrace();
            }
            return i;

其中ExecutionException 可以包含其他异常,例如ABCException。 我的调用代码正在捕获ABCException,这是运行时异常,所以如果发生ExecutionException,我怎么知道是因为ABCExceptionExecutionException 在我的 public call() 方法运行时出现异常。并且调用方法可能有一些ABCException

我应该这样写吗?

 catch (ExecutionException e) {
                     throw new ABCException(e.getMessage());
                     // TODO Auto-generated catch block
                     //e.printStackTrace();
                }

【问题讨论】:

  • 您所说的“ExecutionException 可以在哪里出现其他异常”是什么意思?可以其他一些例外吗?可以包含 其他一些异常吗?您的问题目前还不清楚。
  • @jon sorry..its typo..executionException 由于我的公共 call() 方法运行时出现一些异常。并且调用方法可能有一些 ABCException

标签: java exception concurrency future callable


【解决方案1】:

试试e.getCause() instanceof ABCException

【讨论】:

    【解决方案2】:

    如果在 call() 方法执行过程中发生异常,ExecutorService 会捕获它并将其放入 ExecutionException 中。当你调用 future.get();未来会抛出 ExecutionException,其中包含来自您的调用方法的异常。因此,如果我理解正确,您的代码可能如下所示:

    try {
            future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if(cause instanceof ABCException) {
                // cast throwable to ABCException and rethrow it
                throw (ABCxception) cause;
            }else {
                // do something else
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      相关资源
      最近更新 更多