Dmytro Serdiuk
01/17/2024, 11:51 PMprivate val coroutineExceptionHandler = CoroutineExceptionHandler { _, exception ->
println("Handle $exception in CoroutineExceptionHandler")
}
fun main() = runBlocking {
GlobalScope.launch(coroutineExceptionHandler) {
delay(50)
//println("${coroutineContext[Job]?.parent}")
throw ArithmeticException()
}
delay(100)
println("test")
}
I have two questions, maybe somebody could help me:
1. CoroutineExceptionHandler - I saw somewhere that it’s similar to uncaughtExceptionHandler, but why using it in this code it will “handle” the exception, but as I know uncaughtExceptionHandler is not handling it, it’s last chance to do something before the termination.
2. if not using coroutineExceptionHandler in the launch, the exception would be printed in the console, but coroutine main will continue it’s execution. I thought that after uncaught exception the thread should be terminated.
Thanksephemient
01/18/2024, 12:05 AMprivate val coroutineExceptionHandler = CoroutineExceptionHandler { _, exception ->
println("Handle $exception in CoroutineExceptionHandler")
}
suspend fun main() {
withContext(coroutineExceptionHandler) {
supervisorScope {
launch { throw RuntimeException("a") }
async { throw RuntimeException("b") }
launch { throw RuntimeException("c") }
}
}
}
the CEH prints a and c, which are unhandled. b is "handled" by the Deferred
.
supervisorScope
is different from coroutineScope
or most other coroutine builders; in those cases, there's nothing for CEH to handle because the scope already "handles" it (by cancelling itself and propagating the exception)ephemient
01/18/2024, 12:06 AMGlobalScope
is not connected to your scopeDmytro Serdiuk
01/18/2024, 12:10 AMephemient
01/18/2024, 12:11 AMGlobalScope
which cannot be cancelled, so nothing happensDmytro Serdiuk
01/18/2024, 12:14 AM