【发布时间】: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