How come this `error()` doesn’t crash the app? Giv...
# coroutines
a
How come this
error()
doesn’t crash the app? Given there is no supervisor job I was expecting this to crash the program but it doesn’t. I can see the ‘Starting’ the crash and then ‘job done’ in the logs 🤔
Copy code
suspend fun main() {
    val scope = CoroutineScope(Dispatchers.Main.immediate)
    debugLn { "Starting" }
    scope.launch {
        error("CRASH!")
    }
    delay(500)
    debugLn { "Job done" }
}
s
There’s nothing in the
scope
that you created that would tell the app to crash when one of its jobs fails. What you really want is something more like this:
Copy code
suspend fun main() = coroutineScope {
    debugLn { "Starting" }
    launch {
        error("CRASH!")
    }
    delay(500)
    debugLn { "Job done" }
}
The
coroutineScope
builder creates a scope and then waits for all of its children to complete. That’s what causes it to throw an exception to the containing function if one of its child jobs fails.
s
What @Sam said is what you should do to maintain the same lifecycle as the calling CoroutineScope, but Alex's example is also valid; switching lifecycle by executing/launching something in a brand new CoroutineScope. The new CoroutineScope doesn't have a CoroutineExceptionHandler installed and therefore I'd expect the JVM's Thread Uncaught Exception Handler to take care of it by default (which would crash the app/main)....