我试图理解为什么异常会在没有被?async
包围的情况下沿着层次结构传递。为什么在处理异常时coroutineScope
不需要这样?coroutineScope
launch
fun main() {
runBlocking {
this.launch {// case 1
try {
throw java.lang.IndexOutOfBoundsException()
} catch (e: Exception) {
println("Caught IndexOutOfBoundsException")
}
}
try {
coroutineScope {
val deferred = async {// case 2
throw ArithmeticException()
}
deferred.await()
}
} catch (e: ArithmeticException) {
println("Caught ArithmeticException")
}
try {
val deferred = async {//case 3
throw ArithmeticException()
}
deferred.await()
} catch (e: Exception) {
println("Caught ArithmeticException but passed to root as well")
}
}
}
我当前的输出如下:
Caught IndexOutOfBoundsException
Caught ArithmeticException
Caught ArithmeticException but passed to root as well
Exception in thread "main" java.lang.ArithmeticException
at TryItYourself3Kt$main$1$deferred$1.invokeSuspend(TryItYourself3.kt:26)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:104)
at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:277)
at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:95)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:69)
at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:48)
at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
at TryItYourself3Kt.main(TryItYourself3.kt:5)
at TryItYourself3Kt.main(TryItYourself3.kt)
Process finished with exit code 1
我不确定我是否正确回答了你的问题:
情况 1:我们在异常到达协程机器之前捕获异常,因此协程甚至不知道存在异常。
案例2:
async
是 的孩子coroutineScope
。它们都失败了,但都包含在 中try...catch
,因此我们捕获来自 的异常coroutineScope
。情况 3:
async
是 的子级runBlocking
,因此两者都失败。我们从 捕获失败deferred.await()
,但runBlocking
它本身仍然失败。