Martin Nordholts
04/14/2020, 10:54 AMCoroutineExceptionHandler
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 ignoredrather than “CancellationException is always ignored with CoroutineExceptionHandler”
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)streetsofboston
04/14/2020, 12:53 PMMartin Nordholts
04/14/2020, 1:03 PMLet’s examine the rulesThat article seems to do what I already did; deduce rules by experimentation
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…streetsofboston
04/14/2020, 4:33 PM