java异常从不在相应try语句的主体中抛出

tyu7yeag  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(452)

这个问题在这里已经有了答案

如何处理lambda中的检查异常[重复](1个答案)
上个月关门了。

  1. public CompletableFuture<Set<BusStop>> getBusStops() {
  2. CompletableFuture<Set<BusStop>> stops = new CompletableFuture<Set<BusStop>>();
  3. try {
  4. CompletableFuture<Scanner> sc = CompletableFuture.supplyAsync(() ->
  5. new Scanner(BusAPI.getBusStopsServedBy(serviceId).get()));
  6. stops = sc.thenApply(x -> x.useDelimiter("\n")
  7. .tokens()
  8. .map(line -> line.split(","))
  9. .map(fields -> new BusStop(fields[0], fields[1]))
  10. .collect(Collectors.toSet()));
  11. //sc.close();
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. } catch (ExecutionException e) {
  15. e.printStackTrace();
  16. }
  17. return stops;
  18. }

我有以下错误:

  1. BusService.java:36: error: unreported exception InterruptedException; must be caught or dec
  2. lared to be thrown
  3. new Scanner(BusAPI.getBusStopsServedBy(serviceId).get()));
  4. ^
  5. BusService.java:44: error: exception InterruptedException is never thrown in body of corres
  6. ponding try statement
  7. } catch (InterruptedException e) {
  8. ^
  9. BusService.java:46: error: exception ExecutionException is never thrown in body of correspo
  10. nding try statement
  11. } catch (ExecutionException e) {
  12. ^
  13. 3 errors

我有点困惑,因为编译器说必须捕获异常,但在下一行中它说从未抛出异常?我该如何改变 sc.close() 因为它现在是一个完整的未来。

t9aqgxwy

t9aqgxwy1#

第一个lambda中的扫描器可能会抛出一个异常,您必须在lambda中捕获该异常。
所以你的困惑可能是围绕着这个背景:
有一次你在lambda,这是一个匿名类。在这里你必须抓住例外。
其他时间你在课堂上围绕你的方法。这里没有抛出中断异常。
在lambda中捕获异常可以这样做:

  1. CompletableFuture<Scanner> sc = CompletableFuture.supplyAsync(() -> {
  2. try {
  3. return new Scanner(...);
  4. } catch (Exception e) {
  5. // Handle Exception
  6. }
  7. });

相关问题