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;
  }

I got these errors:

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

I am abit confused, since the compiler said exception must be caught, but in the next line it said exception never thrown? And how should I change the sc.close() since it is now a CompletableFuture.

jie xi lim
  • 37
  • 9
  • you are supposed to catch them in `supplyAsync`... literally [two questions back](https://stackoverflow.com/questions/64937499/letting-completablefuture-exceptionally-handle-a-supplyasync-exception) from the `CompletableFuture` tag – Eugene Nov 23 '20 at 16:47
  • What is the type returned by `BusAPI.getBusStopsServedBy(serviceId)`? Does it returned a CompletableFuture? A regular Future? – VGR Nov 23 '20 at 18:25

1 Answers1

0

The Scanner in your first lambda might throw an Exception, which you have to catch inside the lambda.
So your confusion is probably around this context:

  • onetime you are in the lambda, which is an anonymous class. Here you have to catch the Exception.
  • other time you are in the class around your method. Here is no InterruptedException thrown.

Catching Exception in lambda could be done like this:

CompletableFuture<Scanner> sc = CompletableFuture.supplyAsync(() -> {
    try {
        return new Scanner(...);
    } catch (Exception e) {
        // Handle Exception
    }
});
Elmar Brauch
  • 1,286
  • 6
  • 20