Exception thrown by deferred.await() within a runBlocking treated as unhandled even after caught
After studying the reasons why Kotlin introduced this behavior I found that, if the exceptions weren't propagated this way, it would be complicated to write well-behaved code that gets cancelled in a timely fashion. For example:
runBlocking {
val deferredA = async {
Thread.sleep(10_000)
println("Done after delay")
1
}
val deferredB = async<Int> { throw Exception() }
println(deferredA.await() + deferredB.await())
}
Because a
is the first result we happen to wait for, this code would keep running for 10 seconds and then result in an error and no useful work achieved. In most cases we'd like to cancel everything as soon as one component fails. We could do it like this:
val (a, b) = awaitAll(deferredA, deferredB)
println(a + b)
This code is less elegant: we're forced to await on all results at the same place and we lose type safety because awaitAll
returns a list of the common supertype of all arguments. If we have some
suspend fun suspendFun(): Int {
delay(10_000)
return 2
}
and we want to write
val c = suspendFun()
val (a, b) = awaitAll(deferredA, deferredB)
println(a + b + c)
We're deprived of the opportunity to bail out before suspendFun
completes. We might work around like this:
val deferredC = async { suspendFun() }
val (a, b, c) = awaitAll(deferredA, deferredB, deferredC)
println(a + b + c)
but this is brittle because you must watch out to make sure you do this for each and every suspendable call. It is also against the Kotlin doctrine of "sequential by default"
In conclusion: the current design, while counterintuitive at first, does make sense as a practical solution. It additionally strengthens the rule not to use async-await
unless you're doing parallel decomposition of a task.
Though all the answers are right at there place but let me throw some more light in it that might help other users. It is documented here (Official doc) that:-
If a coroutine encounters exception other than
CancellationException
, it cancels its parent with that exception. This behaviour cannot be overridden and is used to provide stable coroutines hierarchies for structured concurrency which do not depend on CoroutineExceptionHandler implementation. The original exception is handled by the parent (In GlobalScope) when all its children terminate.It does not make sense to install an exception handler to a coroutine that is launched in the scope of the main runBlocking, since the main coroutine is going to be always cancelled when its child completes with exception despite the installed handler.
Hope this will help.