Hello! I have next code: ```private val coroutin...
# coroutines
d
Hello! I have next code:
Copy code
private 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. Thanks
e
perhaps this small modification will help you understand
Copy code
private 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)
1. I don't think "uncaught" isn't a good way to think about it 2.
GlobalScope
is not connected to your scope
d
@ephemient, Thank you for your answers. 1. so it’s not “uncaught” exceptions, it’s mechanism to handle the exception that are propagating to the root. So there are no relationship with uncaughtExceptionHandler 2. but the exception was thrown in the coroutine, that run on the main thread(according to logs), but it wasn’t terminated So as I understand correctly, the next mapping should be applied: Thread <> coroutine uncaughtExceptionHandler <> nothing on coroutine side nothing on thread side <> global exception handler Am I correct? Like two column Thread/coroutine
e
it was thrown in
GlobalScope
which cannot be cancelled, so nothing happens
d
thank you very much for your explanation