Pick the fix
The handler never logs, and the app crashes. Which change makes it fire?
val handler = CoroutineExceptionHandler { _, e -> log("caught $e") }
scope.launch {
launch(handler) {
throw IOException("offline")
}
}Hint 1 of 1
Which coroutine is the root here?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Install the handler on the scope (or the outer launch), not the inner one
Correct. Only the root coroutine's handler is used; the inner child passes the exception to its parent.
Why not the others?
- B Switch the inner launch to async. async never reports to a handler; its exception waits for await.
- C Add
Dispatchers.IOto the inner launch. The dispatcher has nothing to do with exception handling. - D Wrap the outer launch in try/catch. launch returns at once; the exception happens later inside the coroutine.