[英]Kotlin coroutine Job's join method
I have found very strange documentation for join method:我发现 join 方法的文档非常奇怪:
In particular, it means that a parent coroutine invoking join on a child coroutine that was started using launch(coroutineContext) {... } builder throws CancellationException if the child had crashed, unless a non-standard CoroutineExceptionHandler is installed in the context.
特别是,这意味着父协程在子协程上调用 join ,如果子协程已使用 launch(coroutineContext) {... } 构建器启动,则如果子协程崩溃,则抛出 CancellationException,除非在上下文中安装了非标准 CoroutineExceptionHandler。
I'm not sure that CoroutineExceptionHandler will have effect for CancellationException.我不确定 CoroutineExceptionHandler 是否会对 CancellationException 产生影响。 Example:
例子:
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()
}
Output: Output:
handle
join CoroutineExceptionHandler got java.io.IOException
So basically CancellationException will still be thrown regardless any installed handlers.所以基本上 CancellationException 仍然会被抛出,不管任何安装的处理程序。 Am I right?
我对吗?
Yes.是的。 Your innerJob will still throw a
CancellationException
, and in your outer job you'll get a crash, since you don't handle the exception
.你的 innerJob 仍然会抛出一个
CancellationException
,并且在你的外部工作中你会遇到崩溃,因为你不处理exception
。
See: https://pl.kotl.in/1Uqw8nmNS见: https://pl.kotl.in/1Uqw8nmNS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.