这个问题在这里已经有了答案:
如何处理lambda中的检查异常[重复](1个答案)
上个月关门了。
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()
因为它现在是一个完整的未来。
1条答案
按热度按时间t9aqgxwy1#
第一个lambda中的扫描器可能会抛出一个异常,您必须在lambda中捕获该异常。
所以你的困惑可能是围绕着这个背景:
有一次你在lambda,这是一个匿名类。在这里你必须抓住例外。
其他时间你在课堂上围绕你的方法。这里没有抛出中断异常。
在lambda中捕获异常可以这样做: