julian
04/21/2022, 12:32 AMCoroutineExceptionHandler
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:
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)
}
Dmitry Khalanskiy [JB]
04/22/2022, 8:02 AMlaunch(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.
val topLevelScope = CoroutineScope(Job() + coroutineExceptionHandler)
Maybe this is what you want to do?julian
04/22/2022, 5:16 PMlaunch
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.