【发布时间】:2020-11-09 14:16:36
【问题描述】:
我有以下代码片段:
@UseExperimental(ExperimentalCoroutinesApi::class)
fun main() {
fun CoroutineScope.send(id: Int) {
if (id % 11 == 0) cancel()
if (id % 5 == 0) throw IllegalArgumentException()
println(id)
}
fun send() = runBlocking {
val handler = CoroutineExceptionHandler { _, _ ->
println("Something bad happened")
}
val jobs = (1..1000).map {
it to launch(handler) {
send(it)
}
}.toMap()
jobs.values.joinAll()
println("Unable to send message to ids: ${jobs.filterValues { it.isCancelled }.keys.joinToString()}")
}
send()
}
当我运行此代码时,我得到以下结果:
1
2
3
4
Exception in thread "main" java.lang.IllegalArgumentException
我有几个问题:
-
为什么
CoroutineExceptionHandler不处理异常以及为什么它被传播? -
如果我注释掉
if (id % 5 == 0) throw IllegalArgumentException()行,我仍然可以在控制台中看到打印的 ID 11、22、33 等。似乎cancel()并没有立即中断协程。是这样吗?
【问题讨论】: