Question
Puzzling Coroutines behavior in Android ViewModel
I am trying to explore and implement coroutine cancellation / exception recovery mechanism in ViewModel. I discovered that the following code in my ViewModel doesn't catch the exception and crashes the app:
viewModelScope.launch {
try {
supervisorScope {
launch {
throw Exception()
}
}
} catch (e: Exception) {
println("Exception caught")
}
}
But if I replace supervisorScope
with coroutineScope
it gets caught. Shouldn't it get caught in both cases? Can anyone please explain why supervisorScope scope exception cancels its parent scope here?
I tried running following code in Intellij: case1 :
runBlocking {
supervisorScope {
launch {
throw Exception("Supervisor launch exception")
}
}
}
vs case 2:
runBlocking {
launch {
throw Exception("Launch Exception")
}
}
In first case the process finished with exit code 0 and in second case, finished with exit code 1. Why does it give different exit code when both propagates exception to parent?