suspendCancellableTimeoutCoroutine() - cancelled b...
# coroutines
d
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
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
Thanks! So in 3 my
val handler
is not used because
launch
consumes the exception?
y
the other way around. your handler consumes the exception and launch just finishes gracefully.
d
But why I don't see stacktrace and breakpoint doesn't hit in 3?
y
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
Thank you!