This is the answer to the challenge I posted 2 days ago š .
Link to the challenge is here.
The code is here.
As I mentioned in the challenge, exception handling and propagation is a highly complex yet important topic š§. So it's essential to understand it to structure your code properly with coroutines.
First things first - go ahead and take a look at the video š„.
Let's dive in and understand what's happening š.
In the challenge, we had 3 coroutines enclosed within a single "parent" coroutine.
Coroutine 1 throws a RuntimeException, while Coroutine 3 throws a CancellationException.
Coroutine 3 completes faster than all other coroutines and throws an exception. Yet the other 2 coroutines continue with their execution. How come?
We'll answer this question later - but first, let's understand why the 2nd coroutine fails when a RuntimeException is thrown in Coroutine 1.
š One of the key benefits of coroutines is structured concurrency. Structured concurrency ensures that all launched tasks are properly completed or canceled together.
If a child coroutine fails (throws an exception), it also cancels the parent coroutine š„. This helps prevent resource leaks and makes the code easier to understand and maintain.
This happens because an exception is propagated to the parent coroutine. But it works the other way around too - if a parent coroutine fails - it cancels all of its children.
š“ Think of this as pedals and a chain in a bicycle. If one fails - the other one will stop as well.
So, in our case, this is what happens when Coroutine 1 throws a RuntimeException:
1ļøā£ Coroutine 1 Fails
2ļøā£ Exception is propagated to parent coroutine
3ļøā£ Parent coroutine fails
4ļøā£ All coroutines inside parent are canceled (Coroutine 2 in our case)
That's great, but Coroutine 3 fails first. So why doesn't it cancel the parent coroutine?
This is the whole point of this challenge.
āØ CancellationException is treated differently by the coroutine framework. When the CancellationException is thrown - the framework treats it as a normal completion of the coroutine.
It's still an exception, but it serves an entirely different purpose than all others. That's why this exception does not propagate to the parent coroutine in our example.
š Have you had nasty bugs with exceptions in Kotlin coroutines? Share your experiences belowš.
Comments