我在与协程一起玩耍,发现一些非常奇怪的行为。我想使用转换项目中的一些异步请求suspendCoroutine()。这是显示此问题的代码。
在第一种情况下,当在runBlocking协程中调用suspend函数时,来自延续的异常进入catch块,然后runBlocking成功完成。但是在第二种情况下,当创建新的async协程时,异常会通过catch块并使整个程序崩溃。
package com.example.lib
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
object Test {
fun runSuccessfulCoroutine() {
runBlocking {
try {
Repository.fail()
} catch (ex: Throwable) {
println("Catching ex in runSuccessfulCoroutine(): $ex")
}
}
}
fun runFailingCoroutine() {
runBlocking {
try {
async { Repository.fail() }.await()
} catch (ex: Throwable) {
println("Catching ex in runFailingCoroutine(): $ex")
}
}
}
}
object Repository {
suspend fun fail(): Int = suspendCoroutine { cont …Run Code Online (Sandbox Code Playgroud)