https://kotlinlang.org logo
Title
m

Martin Nordholts

04/14/2020, 10:54 AM
Will
CoroutineExceptionHandler
never handle
CancellationException
? That seems to be the case (see example program in thread) but I can’t find a clear authoritative statement on that this is the case. For example, docs for interface CoroutineExceptionHandler states
when no handler is installed […] CancellationException […] is ignored
rather than “CancellationException is always ignored with CoroutineExceptionHandler
1
fun main() = runBlocking {
    val scope =
        CoroutineScope(Job() + CoroutineExceptionHandler { _: CoroutineContext, throwable: Throwable ->
            println("handled  $throwable")
        })

    val job = scope.launch {
        try {
            throw CancellationException()
        } catch (e: CancellationException) {
            println("cancelled, rethrowing");
            throw e
        }
    }

    job.join()
    println("program completed")
}
but “handled …” is not printed (But if I change to
throw ArithmeticException()
then it is indeed printed)
s

streetsofboston

04/14/2020, 12:53 PM
Yes, it will never handle it. https://link.medium.com/WPEB31h7F5
m

Martin Nordholts

04/14/2020, 1:03 PM
Thanks, but in what way is that an authorative source? 🤔
Let’s examine the rules
That article seems to do what I already did; deduce rules by experimentation
I looked at the coroutine implementation and found this:
if (finalException != null) {
            val handled = cancelParent(finalException) || handleJobException(finalException)
            if (handled) (finalState as CompletedExceptionally).makeHandled()
        }
and inside cancelParent() we can find (among other things)
isCancellation = cause is CancellationException
and by following the code a bit more this is to me authorative enough…
s

streetsofboston

04/14/2020, 4:33 PM
It is not an authorative source (it’s just me 🙂 ), but I looked at the official kotlin documentation and started experimenting from there.