【发布时间】:2021-06-23 09:24:22
【问题描述】:
我在文档中找到了下一条语句:
取消异常是透明的,默认情况下是展开的:
val handler = CoroutineExceptionHandler { _, exception -> println("CoroutineExceptionHandler got $exception")
}
val job = GlobalScope.launch(handler) {
val inner = launch { // all this stack of coroutines will get cancelled
launch {
launch {
throw IOException() // the original exception
}
}
}
try {
inner.join()
} catch (e: CancellationException) {
println("Rethrowing CancellationException with original cause")
throw e // cancellation exception is rethrown, yet the original IOException gets to the handler
}
}
job.join()
此文档在此代码中的含义是什么?
2021 年 3 月 27 日更新
import kotlinx.coroutines.*
import java.io.*
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("CoroutineExceptionHandler got $exception")
}
val job = GlobalScope.launch(handler) {
launch {
throw IOException() // the original exception
}
launch {
throw CancellationException("Test", ArithmeticException("Arithmetic"))
}
}
job.join()
}
为什么在这种情况下结果是:
CoroutineExceptionHandler got java.io.IOException
没有算术异常?
【问题讨论】:
标签: kotlin kotlin-coroutines kotlin-android-extensions cancellation