【问题标题】:GlobalScope coroutine not logging error to consoleGlobalScope 协程未将错误记录到控制台
【发布时间】:2019-08-28 03:26:48
【问题描述】:
为什么下面的代码没有将 TimeoutCancellationException 记录到控制台?
@Test fun noExceptionLogged(){
GlobalScope.launch{
withTimeout(4000) {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
}
Thread.sleep(20_000)
}
【问题讨论】:
标签:
kotlin
kotlin-coroutines
【解决方案1】:
由于GlobalScope 的性质,它似乎是这样工作的。它不能被取消,所以它吞噬了CancellationException。
GlobalScope.launch { // won't print anything
throw CancellationException()
}
GlobalScope.launch { // will print stacktrace
throw RuntimeException()
}
runBlocking { // will print stackrace
throw RuntimeException()
}
GlobalScope.launch { // will print "Hello!"
try {
throw CancellationException()
} catch (e: Exception) {
println("Hello!")
}
}