Predict the output
Child B throws. Which children finish?
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default + handler)
scope.launch { delay(500); log("A done") }
scope.launch { delay(100); throw IllegalStateException("B failed") }
scope.launch { delay(500); log("C done") }Hint 1 of 2
What does a SupervisorJob do when a child fails?
Hint 2 of 2
Where do uncaught launch exceptions go?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A A and C finish; B's error goes to the handler
Correct. A supervisor doesn't cancel siblings, and the handler receives B's uncaught exception.
Why not the others?
- B Nothing finishes; the whole scope is cancelled. That would be a regular Job().
- C A and C finish and the error disappears. The error is not swallowed; it goes to the CoroutineExceptionHandler.
- D Only A finishes because C started after B. All three start right away; order doesn't matter here.
Text version
With Job (child B fails)
- B throws
- B's failure cancels the scope's Job
- A and C are cancelled
- The handler gets B's exception
scope: ⊘ cancelledchild A: ⊘ cancelledchild B: ✕ failedchild C: ⊘ cancelled
With SupervisorJob (child B fails)
- B throws
- The supervisor keeps the scope alive
- The handler gets B's exception
- A and C complete
scope: ● activechild A: ✓ completedchild B: ✕ failedchild C: ✓ completed