Java Reference
In-Depth Information
11.2.2. Dealing with errors
The code we developed so far works correctly if everything goes smoothly. But what happens if
the price calculation generates an error? Unfortunately, in this case you'll get a particularly
negative outcome: the exception raised to signal the error will remain confined in the thread,
which is trying to calculate the product price, and will ultimately kill it. As a consequence, the
client will remain blocked forever, waiting for the result of the get method to arrive.
The client can prevent this problem by using an overloaded version of the get method that also
accepts a timeout. It's a good practice to always use a timeout to avoid similar situations
elsewhere in your code. This way the client will at least avoid waiting indefinitely, but when the
timeout expires, it will just be notified with a TimeoutException. As a consequence, it won't have
a chance to discover what really caused that failure inside the thread that was trying to calculate
the product price. To make the client aware of the reason the shop wasn't able to provide the
price of the requested product, you have to propagate the Exception that caused the problem
inside the CompletableFuture through its completeExceptionally method. This refines listing
11.4 to give the code shown in the listing that follows.
Listing 11.6. Propagating an error inside the CompletableFuture
The client will now be notified with an ExecutionException (which takes an Exception
parameter containing the cause—the original Exception thrown by the price calculation method).
So, for example, if that method throws a RuntimeException saying “product not available,” the
client will get an ExecutionException like the following:
java.util.concurrent.ExecutionException: java.lang.RuntimeException: product not available
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:2237)
at lambdasinaction.chap11.AsyncShopClient.main(AsyncShopClient.java:14)
... 5 more
 
Search WWH ::




Custom Search