Exception handling in Kotlin Coroutines
A very important part of how coroutines behave is their exception handling. Just as a program breaks when an uncaught exception slips by, a coroutine breaks in the case of an uncaught exception. This behavior is nothing new: for instance, threads also end in such cases. The difference is that coroutine builders also cancel their parents, and each cancelled parent cancels all its children. Let's look at the example below. Once a coroutine receives an exception, it cancels itself and propagates the exception to its parent (
launch). The parent cancels itself and all its children, then it propagates the exception to its parent (
runBlocking is a root coroutine (it has no parent), so it just ends the program (
runBlocking rethrows the exception).
launch coroutines wouldn't change anything. Exception propagation is bi-directional: the exception is propagated from child to parent, and when those parents are cancelled, they cancel their children. Thus, if exception propagation is not stopped, all coroutines in the hierarchy will be cancelled.
Stop breaking my coroutines
Catching an exception before it breaks a coroutine is helpful, but any later is too late. Communication happens via a job, so wrapping a coroutine builder with a try-catch is not helpful at all.
The most important way to stop coroutines breaking is by using a
SupervisorJob. This is a special kind of job that ignores all exceptions in its children.
SupervisorJob is generally used as part of a scope in which we start multiple coroutines (more about this in the Constructing coroutine scope chapter).
A common mistake is to use a
SupervisorJob as an argument to a parent coroutine, like in the code below. It won't help us handle exceptions, because in such a case
SupervisorJob has only one direct child, namely the
launch defined at 1 that received this
SupervisorJob as an argument. So, in such a case there is no advantage of using
Job (in both cases, the exception will not propagate to
runBlocking because we are not using its job).
It would make more sense if we used the same job as a context for multiple coroutine builders because each of them can be cancelled, but they won’t cancel each other.
Another way to stop exception propagation is to wrap coroutine builders with
supervisorScope. This is very convenient as we still keep a connection to the parent, yet any exceptions from the coroutine will be silenced.
supervisorScope is just a suspending function and can be used to wrap suspending function bodies. This and other functionalities of
supervisorScope will be described better in the next chapter. The common way to use it is to start multiple independent tasks.
Another way to stop exception propagation is to use
coroutineScope. Instead of influencing a parent, this function throws an exception that can be caught using try-catch (in contrast to coroutine builders). Both will be described in the next chapter.
supervisorScope cannot be replaced with
withContext(SupervisorJob())! Take a look at the below snippet.
The problem here is that
Job is the only context that is not inherited. Each coroutine needs its own job, and passing a job to a coroutine makes it a parent. So here
SupervisorJob is a parent of
withContext coroutine. When a child has an exception, it propagates to
coroutine coroutine, cancels its
Job, cancels children, and throws an exception. The fact that
SupervisorJob is a parent changes nothing.
So, we know how to stop exception propagation, but sometimes this is not enough. In the case of an exception, the
async coroutine builder breaks its parent, just like
launch and other coroutine builders that have a relation with their parents. However, what if this process is silenced (for instance, using
await is called? Let's look at the following example:
We have no value to return since the coroutine ended with an exception, so instead the
MyException exception is thrown by
await. This is why
MyException is printed. The other
async finishes uninterrupted because we’re using the
CancellationException does not propagate to its parent
If an exception is a subclass of
CancellationException, it will not be propagated to its parent. It will only cause cancellation of the current coroutine.
CancellationException is an open class, so it can be extended by our own classes or objects.
In the above snippet, we start two coroutines with builders at 1 and 4. At 3, we throw a
MyNonPropagatingException exception, which is a subtype of
CancellationException. This exception is caught by
launch (started at 4). This builder cancels itself, then it also cancels its children, namely the builder defined at 5. The second
launch is not affected, so it prints "Will be printed" after 2 seconds.
Coroutine exception handler
When dealing with exceptions, sometimes it is useful to define default behavior for all of them. This is where the
CoroutineExceptionHandler context comes in handy. It does not stop the exception propagating, but it can be used to define what should happen in the case of an exception (by default, it prints the exception stack trace).
This context is useful on many platforms to add a default way of dealing with exceptions. For Android, it often informs the user about a problem by showing a dialog or an error message.
Exception handling is an important part of the kotlinx.coroutines library. Over time, we will inevitably come back to these topics. For now, I hope that you understand how exceptions propagate from child to parent in basic builders, and how they can be stopped. Now it’s time for a long-awaited, strongly connected topic. Time to talk about coroutine scope functions.