【发布时间】:2019-03-03 05:25:33
【问题描述】:
正如标题所说,为什么挂起函数会在finally 中抛出异常?
对于常规函数,finally-block 会执行所有函数:
import kotlinx.coroutines.*
fun main() {
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception")
}
val job = GlobalScope.launch(handler) {
launch {
// the first child
try {
println("inside try")
delay(1000)
} finally {
println("Children are cancelled, but exception is not handled until all children terminate")
Thread.sleep(1000)
println("thread.sleep executed")
//foo()
println("The first child finished its non cancellable block")
}
}
launch {
// the second child
delay(10)
println("Second child throws an exception")
throw ArithmeticException()
}
}
Thread.sleep(1000000)
println("complete")
}
例如,当我执行Thread.sleep(1000) 时,它会打印:
“第一个孩子完成了它的不可取消的块”
但如果我将该行更改为delay(1000),它不会。
据我了解,在finally-block 中,如果存在异常,则会在执行整个块后抛出异常。
但在这种情况下,delay 会导致此异常提前抛出。
另一方面,Thread.sleep 没有。
谁能帮忙解释一下?
【问题讨论】:
-
分享你的代码
标签: kotlin kotlinx.coroutines kotlin-coroutines