This code:
fun main() {
runBlocking {
try {
val deferred = async { throw Exception() }
deferred.await()
} catch (e: E
A normal CoroutineScope
(which is created by runBlocking
) immediately cancels all child coroutines when one of them throws an exception. This behaviour is documented here: https://kotlinlang.org/docs/reference/coroutines/exception-handling.html#cancellation-and-exceptions
You can use a supervisorScope
to get the behaviour you want. If a child coroutine fails inside a supervisor scope, it will not immediately cancel the other children. The children will only be cancelled if the exception is unhandled.
For more info, see here: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/supervisor-scope.html
fun main() {
runBlocking {
supervisorScope {
try {
val deferred = async { throw Exception() }
deferred.await()
} catch (e: Exception) {
println("Caught $e")
}
}
}
println("Completed")
}