title: Why Java 8 CompletableFuture thenCompose generates different exception depending on the order of completion?
body: <p>I have encountered strange behavior of Java 8 CompletableFuture thenCompose method. I have two tests that differ only in order of execution. Both tests simulate failure in the CompletableFuture generated in thenCompose.</p>
  
  <pre><code>@Test
  public void completedAfter() {
      CompletableFuture&lt;String&gt; future1 = new CompletableFuture&lt;&gt;();
      CompletableFuture&lt;String&gt; future2 = new CompletableFuture&lt;&gt;();
  
      future1.thenCompose(x -&gt; future2).whenComplete((r, e) -&gt; System.out.println("After: " + e));
  
      future1.complete("value");
      future2.completeExceptionally(new RuntimeException());
  }
  
  @Test
  public void completedBefore() {
      CompletableFuture&lt;String&gt; future1 = new CompletableFuture&lt;&gt;();
      CompletableFuture&lt;String&gt; future2 = new CompletableFuture&lt;&gt;();
  
      future1.complete("value");
      future2.completeExceptionally(new RuntimeException());
  
      future1.thenCompose(x -&gt; future2).whenComplete((r, e) -&gt; System.out.println("Before: " +e));
  }
  </code></pre>
  
  <p>The output is:</p>
  
  <pre><code>After: java.util.concurrent.CompletionException: java.lang.RuntimeException
  Before: java.lang.RuntimeException
  </code></pre>
  
  <p>The question is, why is the exception wrapped in <code>CompletionException</code> in one case but not in the other?</p>
  
  <p><strong>Update: <a href="https://bugs.openjdk.java.net/browse/JDK-8068432" rel="nofollow">Here</a> is related bug report. It has been marked and resolved as a bug in JDK.</strong></p>