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

giso

03/11/2019, 4:14 PM
Hi there. I have a suspend function in which a resource is opened and later closed in a finally block. Upon cancellation I would expect to receive a CancellationException. But I don't receive any und the finally block is not executed. Does anyone know why?
a

Allan Wang

03/11/2019, 4:15 PM
Where are you catching the exception? Subsequent suspend functions don’t run upon cancellation. Your best bet may be to add a cancellation exception handler on launch
g

giso

03/11/2019, 4:21 PM
I catch it inside the function. And because this function is part of a library, I don't have control over how it is launched
Copy code
suspend fun doStuff() {
    try {
        val resource = openResource()
        callOtherSupendFunction(resource)
    } catch (e : CancellationException) {
        // never reached here
    } finally {
        resource.close() // not executed when cancelled
    }
}
I found the issue. Inside
callOtherSupendFunction()
was a
suspendCoroutine{ }
block, which I had to replace with
suspendCancellableCoroutine{ }
block to receive the CancellableException.
3 Views