流API中如何处理InterruptedException和ExecutionException

时间:2019-08-02 15:13:30

标签: java

我有项目列表,并使用流API进行迭代,并从Future对象获取值。它的抛出编译时异常。在这种情况下如何处理

我尝试了包装方法,但问题仍然没有解决。

Future<Map<Integer, String>> serviceInfoFuture = executor.submit(new Callable<Map<Integer, String>>() {
                    @Override
                    public Map<Integer, String> call() throws Exception {
                        return serviceUtil.getServiceInfoForTenant(Integer.parseInt(tenantId));
                    }
                });
List<String> listOfServiceNameAndIds = response.getItems().stream().map(e -> uncheckCall(serviceInfoFuture.get().get(Integer.parseInt(e)+"="+e))).collect(Collectors.toList());

public static <T> T uncheckCall(Callable<T> callable) {
    try { return callable.call(); }
    catch (RuntimeException e) { throw e; }
    catch (InterruptedException  |ExecutionException e) { throw new RuntimeException(e); }
    catch (Exception e){throw new RuntimeException(e);}
}

1 个答案:

答案 0 :(得分:2)

您没有处理InterruptedException抛出的ExecutionExceptionserviceInfoFuture.get()

.map(e -> {
  try {
    return uncheckCall(serviceInfoFuture.get().get(Integer.parseInt(e) + "=" + e));
  } catch (InterruptedException | ExecutionException exception) {
    throw new RuntimeException(exception);
  }
})

uncheckCall仅处理callable.call()中引发的异常。