https://kotlinlang.org logo
#coroutines
Title
# coroutines
d

Dmitry Khasanov

12/10/2019, 12:10 PM
suspendCancellableTimeoutCoroutine() - cancelled by timeout 1. app crashes
runBlocking {
suspendCancellableTimeoutCoroutine()
}
2. app doesn't crash
runBlocking {
launch {
suspendCancellableTimeoutCoroutine()
}
}
3. app doesn't crash, but I don't see stacktrace in logcat
runBlocking {
val handler = CoroutineExceptionHandler { _, e -> e.printStackTrace() }
launch(handler) {
suspendCancellableTimeoutCoroutine()
}
}
4. This is the behavior that I have now, it works as needed
runBlocking {
try {
suspendCancellableTimeoutCoroutine()
} catch(e: CancellableException) {
e.printStackTrace()
}
}
Could anyone explain to me 2 and 3, please?
y

yousefa2

12/10/2019, 12:21 PM
In 3, you already have an exception handler which means that the cancellation exception is consumed by the handler and that’s it. In 2, the
launch
coroutine consumes the cancellation exception and doesn’t propagate it to its parent (runBlocking). In 1, no one is consuming the exception so it ends up being propagated up the chain and unhandled exception = crash.
d

Dmitry Khasanov

12/10/2019, 12:28 PM
Thanks! So in 3 my
val handler
is not used because
launch
consumes the exception?
y

yousefa2

12/10/2019, 12:32 PM
the other way around. your handler consumes the exception and launch just finishes gracefully.
d

Dmitry Khasanov

12/10/2019, 12:36 PM
But why I don't see stacktrace and breakpoint doesn't hit in 3?
y

yousefa2

12/10/2019, 12:44 PM
Actually, I am wrong. Cancellation exceptions are ignored by handlers. See here for more info https://kotlinlang.org/docs/reference/coroutines/exception-handling.html#cancellation-and-exceptions
👍 1
d

Dmitry Khasanov

12/10/2019, 12:48 PM
Thank you!