It seems like it is no longer the case that a `Cor...
# coroutines
j
It seems like it is no longer the case that a
CoroutineExceptionHandler
installed on a top-level/root
launch
coroutine builder will catch uncaught exceptions. That's what I found with coroutines
1.6.1
. The handler must be installed on the
CoroutineScope
itself. Just want to sanity check that this is actually the case, not something weird that I'm doing and not realizing. Here's sample code of what used to catch, but seems to no longer:
Copy code
fun main() {

    val coroutineExceptionHandler = CoroutineExceptionHandler { coroutineContext, exception ->
        println("Handle $exception in CoroutineExceptionHandler")
    }

    val topLevelScope = CoroutineScope(Job())

    topLevelScope.launch {
        launch(coroutineExceptionHandler) {
            throw RuntimeException("RuntimeException in nested coroutine")
        }
    }

    Thread.sleep(100)
}
d
Looks like the correct behavior to me. The
launch(coroutineExceptionHandler)
coroutine fails, but the exception is not uncaught; instead, it is passed to
topLevelScope
. There, the exception is uncaught, but the
topLevelScope
itself does not know about the handler.
Copy code
val topLevelScope = CoroutineScope(Job() + coroutineExceptionHandler)
Maybe this is what you want to do?
j
Thanks @Dmitry Khalanskiy [JB]. Yes. That works. However this wasn't the behavior I'd observed a while back. Up till recently, not only could the handler be used on the scope, it could also be used on a top-level
launch
and it would be caught. I was confirming that there had been a change at some point to coroutines, such that a handler on a top-level
launch
no longer gets invoked.