Reputation: 7249
Why is the code below not logging to the console a TimeoutCancellationException?
@Test fun noExceptionLogged(){
GlobalScope.launch{
withTimeout(4000) {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
}
Thread.sleep(20_000)
}
Upvotes: 1
Views: 698
Reputation: 8442
It seems like it works like this due to GlobalScope
nature. It cannot be canceled so it swallows 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!")
}
}
Upvotes: 1