Skip to content

Commit c89a630

Browse files
committed
Exception handling in Java CompletableFuture
1 parent 3e58c9e commit c89a630

1 file changed

Lines changed: 38 additions & 13 deletions

File tree

‎java-examples/java-core/src/test/java/com/hellokoding/java/concurrent/CompletableFutureExceptionHandlingTest.java‎

Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,51 +4,76 @@
44

55
import java.util.concurrent.CompletableFuture;
66

7-
import static org.assertj.core.api.Java6Assertions.assertThat;
8-
97
public class CompletableFutureExceptionHandlingTest {
108
@Test
11-
public void handle() {
9+
public void handleWithException() {
1210
CompletableFuture completableFuture = CompletableFuture
1311
.supplyAsync(() -> Integer.parseInt("s"))
1412
.handleAsync((result, e) -> {
1513
if (e != null) {
1614
System.out.println(e.getMessage());
1715
return "Error!";
1816
} else {
19-
return result;
17+
return result + 1;
2018
}
2119
})
2220
.thenAcceptAsync(System.out::println);
21+
}
2322

24-
assertThat(completableFuture.join())
25-
.isNull();
23+
@Test
24+
public void handleWithoutExceptions() {
25+
CompletableFuture completableFuture = CompletableFuture
26+
.supplyAsync(() -> 1)
27+
.handleAsync((result, e) -> {
28+
if (e != null) {
29+
System.out.println(e.getMessage());
30+
return "Error!";
31+
} else {
32+
return result + 1;
33+
}
34+
})
35+
.thenAcceptAsync(System.out::println);
2636
}
2737

2838
@Test
29-
public void exceptionally() {
39+
public void exceptionallyWithException() {
3040
CompletableFuture completableFuture = CompletableFuture
3141
.supplyAsync(() -> Integer.parseInt("s"))
3242
.exceptionallyAsync((e) -> {
3343
System.out.println(e.getMessage());
34-
return null;
44+
return 0;
3545
})
3646
.thenAcceptAsync(System.out::println);
47+
}
3748

38-
assertThat(completableFuture.join())
39-
.isNull();
49+
@Test
50+
public void exceptionallyWithoutExceptions() {
51+
CompletableFuture completableFuture = CompletableFuture
52+
.supplyAsync(() -> 1)
53+
.exceptionallyAsync((e) -> {
54+
System.out.println(e.getMessage());
55+
return 0;
56+
})
57+
.thenAcceptAsync(System.out::println);
4058
}
4159

4260
@Test
43-
public void whenComplete() {
61+
public void whenCompleteWithException() {
4462
CompletableFuture completableFuture = CompletableFuture
4563
.supplyAsync(() -> Integer.parseInt("s"))
4664
.whenCompleteAsync((result, e) -> {
4765
if (e != null) System.out.println(e.getMessage());
4866
})
4967
.thenAcceptAsync(System.out::println);
68+
}
5069

51-
assertThat(completableFuture.join())
52-
.isNull();
70+
@Test
71+
public void whenCompleteWithoutExceptions() {
72+
CompletableFuture completableFuture = CompletableFuture
73+
.supplyAsync(() -> 1)
74+
.whenCompleteAsync((result, e) -> {
75+
if (e != null) System.out.println(e.getMessage());
76+
})
77+
.thenAcceptAsync(System.out::println);
5378
}
5479
}

0 commit comments

Comments
 (0)