Exception thrown by deferred.await() within a runBlocking treated as unhandled even after caught

前端 未结 4 1031
时光说笑
时光说笑 2021-02-14 10:20

This code:

fun main() {
    runBlocking {
        try {
            val deferred = async { throw Exception() }
            deferred.await()
        } catch (e: E         


        
4条回答
  •  悲&欢浪女
    2021-02-14 10:45

    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")
    }
    

提交回复
热议问题