【问题标题】:exception XXX is never thrown in body of corresponding try statement [duplicate]异常 XXX 永远不会在相应的 try 语句的主体中引发 [重复]
【发布时间】:2020-11-23 16:36:18
【问题描述】:
public CompletableFuture<Set<BusStop>> getBusStops() {
    CompletableFuture<Set<BusStop>> stops = new CompletableFuture<Set<BusStop>>();
    try {
      CompletableFuture<Scanner> sc = CompletableFuture.supplyAsync(() ->
              new Scanner(BusAPI.getBusStopsServedBy(serviceId).get()));

      stops = sc.thenApply(x -> x.useDelimiter("\n")
              .tokens()
              .map(line -> line.split(","))
              .map(fields -> new BusStop(fields[0], fields[1]))
              .collect(Collectors.toSet()));
      //sc.close();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }
    return stops;
  }

我收到了这些错误:

BusService.java:36: error: unreported exception InterruptedException; must be caught or dec
lared to be thrown
              new Scanner(BusAPI.getBusStopsServedBy(serviceId).get()));
                                                                   ^
BusService.java:44: error: exception InterruptedException is never thrown in body of corres
ponding try statement
    } catch (InterruptedException e) {
      ^
BusService.java:46: error: exception ExecutionException is never thrown in body of correspo
nding try statement
    } catch (ExecutionException e) {
      ^
3 errors

我有点困惑,因为编译器说必须捕获异常,但在下一行它说从不抛出异常? 我应该如何更改sc.close(),因为它现在是 CompletableFuture。

【问题讨论】:

  • 你应该在supplyAsync 中捕获它们...字面意思是two questions back 来自CompletableFuture 标签
  • BusAPI.getBusStopsServedBy(serviceId)返回的类型是什么?它是否返回了 CompletableFuture?一个普通的未来?

标签: java exception completable-future


【解决方案1】:

第一个 lambda 中的 Scanner 可能会引发异常,您必须在 lambda 中捕获该异常。
所以你的困惑可能是围绕这个上下文:

  • 有一次你在 lambda 中,它是一个匿名类。在这里你必须捕获异常。
  • 其他时候你在课堂上围绕你的方法。这里没有抛出 InterruptedException。

在 lambda 中捕获异常可以这样完成:

CompletableFuture<Scanner> sc = CompletableFuture.supplyAsync(() -> {
    try {
        return new Scanner(...);
    } catch (Exception e) {
        // Handle Exception
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 2011-05-18
    • 2011-11-06
    • 2017-07-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多