【发布时间】:2023-03-03 18:13:02
【问题描述】:
所以基于 Kotlin 对协程的介绍,在 Cancellation and Timeouts -> Run non-cancellable block 我找到了以下解释:Any attempt to use a suspending function in the finally block [...] causes CancellationException 但是在运行时:
fun runPlayground() = runBlocking {
val job = launch {
try {
repeat(1000) { i ->
Log.d("XXX", "job: I'm sleeping $i ...")
delay(500L)
}
} finally {
doWorld() // logs "World" after 1s delay
delay(2000L)
Log.d("XXX", "job: I'm running finally")
}
}
delay(1300L) // delay a bit
Log.d("XXX", "main: I'm tired of waiting!")
job.cancelAndJoin() // cancels the job and waits for its completion
Log.d("XXX", "main: Now I can quit.")
}
记录结果:
D/XXX: job: I'm sleeping 0 ...
D/XXX: job: I'm sleeping 1 ...
D/XXX: job: I'm sleeping 2 ...
D/XXX: main: I'm tired of waiting!
D/XXX: main: Now I can quit.
最终块没有被执行可能是因为在那里运行挂起函数,但我希望在我从以下位置运行代码时得到CancellationException:
try {
runPlayground()
} catch (e: CancellationException) {
Log.d("XXX", e.message)
}
异常是否在协程内部处理?
【问题讨论】:
标签: android kotlin kotlin-coroutines