...

/

Other Ways of Exception Handling

Other Ways of Exception Handling

Learn other ways that coroutines handle exceptions.

supervisorScope

Another way to stop exception propagation is to wrap coroutine builders with supervisorScope. This is very convenient as we still connect to the parent, yet any exceptions from the coroutine will be silenced.

package kotlinx.coroutines.app
import kotlinx.coroutines.*

fun main(): Unit = runBlocking {
   supervisorScope {
       launch {
           delay(1000)
           throw Error("Some error")
       }

       launch {
           delay(2000)
           println("Will be printed")
       }
   }
   delay(1000)
   println("Done")
}
Handling exception using supervisorScope

The supervisorScope function is just a suspending function and it can be used to wrap suspending function bodies. This and other functionalities of supervisorScope will be described better in the next lesson. The standard way to use it is to start multiple ...