Newbie
Newbie

Reputation: 7249

GlobalScope coroutine not logging error to console

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

Answers (1)

Andrei Tanana
Andrei Tanana

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

Related Questions