top of page

šŸŒŸ Do you know why CancellationException is special in coroutines?



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šŸ‘‡.

22 views0 comments

Comments


bottom of page