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了,我应该如何更改。
您第一个Lambda中的扫描程序可能会引发异常,您必须在Lambda内部捕获该异常。
因此,您可能会在以下情况下感到困惑:
在lambda中捕获异常可以像这样完成:
CompletableFuture<Scanner> sc = CompletableFuture.supplyAsync(() -> {
try {
return new Scanner(...);
} catch (Exception e) {
// Handle Exception
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句