【发布时间】:2021-03-29 22:06:29
【问题描述】:
我发现 join 方法的文档很奇怪:
特别是,它意味着父协程调用 join 使用 launch(coroutineContext) { ... 如果孩子崩溃了,生成器会抛出 CancellationException, 除非在 上下文。
我不确定 CoroutineExceptionHandler 是否会对 CancellationException 产生影响。 示例:
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("CoroutineExceptionHandler got $exception")
}
val job = GlobalScope.launch(handler) {
val inner = launch { // all this stack of coroutines will get cancelled
throw IOException() // the original exception
}
try {
inner.join()
} catch (e: CancellationException) {
println("handle join")
}
}
job.join()
}
输出:
handle
join CoroutineExceptionHandler got java.io.IOException
所以基本上 CancellationException 仍然会被抛出,无论是否安装了任何处理程序。 我说的对吗?
【问题讨论】:
-
是的,我认为文档是错误的。除了顶级协程上下文(其
Job元素没有父级)之外,协程异常处理程序在任何地方都被忽略。
标签: android kotlin kotlin-coroutines