Java 11: advanced patterns with CompletableFuture and handling Handling in a Chained Pipeline
I'm upgrading from an older version and I tried several approaches but none seem to work. I'm working with unexpected behavior when using `CompletableFuture` in Java 11, particularly when chaining multiple stages and handling exceptions. I have the following code that processes a list of integers, transforming them into their square roots and handling any potential exceptions that may arise during the computation: ```java import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class CompletableFutureExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(4, 9, -1, 16); CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> numbers) .thenApplyAsync(nums -> nums.stream().map(num -> { if (num < 0) throw new IllegalArgumentException("Negative number"); return Math.sqrt(num); }).toList()) .exceptionally(ex -> { System.out.println("behavior occurred: " + ex.getMessage()); return List.of(); }) .thenAccept(result -> System.out.println("Results: " + result)); try { future.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } ``` When I run this code, I expect to see the results of the square roots of the non-negative numbers and a message about the behavior for the negative number. However, the output shows `Results: []` without printing any behavior message. It seems the `exceptionally` block is being triggered, but I am not sure why the behavior isn't being caught as expected. I've tried modifying the exception handling to include more logging, but I still need to pinpoint the scenario. Based on the Java documentation, the `exceptionally` block should catch exceptions thrown in the preceding stages, but it seems to be skipping the behavior handling for the negative number. What am I missing here? Is there a better way to structure this chain to handle exceptions properly? Any insights would be greatly appreciated! What am I doing wrong? Any ideas what could be causing this? I recently upgraded to Java 3.10.