I test coroutineExceptionHandler.
Here is my code.
fun createExceptionHandler(name: String) = CoroutineExceptionHandler { context, throwable ->
println("[${Thread.currentThread().name} - $name] Caught $throwablen${context[CoroutineExceptionHandler]}")
}
@Test
fun coroutineScope_exceptionHandle() = runBlocking<Unit> {
val coroutineScope = CoroutineScope(Job() + createExceptionHandler("supervisor"))
coroutineScope.launch(createExceptionHandler("launch1")) {
launch(CoroutineName("launch2") + createExceptionHandler("launch2")) {
throw Exception("[${Thread.currentThread().name}] Error !")
}
launch(CoroutineName("launch3")) {
println("[${Thread.currentThread().name}] launch3")
}
}
delay(1000L)
}
Result:
[DefaultDispatcher-worker-3 @launch3#6] launch3
[DefaultDispatcher-worker-2 @launch2#5 - launch1] Caught java.lang.Exception: [DefaultDispatcher-worker-2 @launch2#5] Error !
...
I expect the exception handled by coroutineScope’s handler named supervisor.
Could you please explain why the exception handled by launch1 handler?