Exceptions in Coroutines Flashcards
What happened if a coroutine suddenly happened?
When a coroutine suddenly fails with an exception, it will propagate said exception up to its parent. Then the parent do the following tasks.
- It will cancel the rest of its children
- It cancels itself
- It propagates exception up to its parent
The exception will reach the root of hierarchy and all coroutines that the coroutinescope started will get cancelled too.
What is a SupervisorJop in coroutines?
With a supervisor job, the failure of a child doesn’t affect other children. A SupervisorJob won’t cancel itself or the rest of its children. The SupevisorJob won’t propagate the exception either, and will let the child coroutine handle it.
Warning: A SupervisorJob only works as described when it’s part of a scope either created using supervisorscope or CoroutineScope(SupervisorJob())
How to handle uncaught exception by launch coroutine builder?
With launch, exceptions will be thrown as soon as they happen.
scope.launch { try { codeThatCanThrowExceptions() } catch(e: Exception) { // Handle exception } }
How to handle exceptions in async coroutine builder?
When async is used as a root coroutine(coroutines that are a direct child of a CoroutineScope instance or supervisorscope), exceptions are not thrown automatically, instead, they are thrown when you call await() function.
supervisorScope { val deferred = async { codeThatCanThrowExceptions() } try { deferred.await() } catch(e: Exception) { // Handle exception thrown in async } }
What is CoroutineExceptionHandler?
The CoroutineExceptionHandler is an optional element of a CoroutineContext allowing you to handle the uncaught exceptions.
val handler = CoroutineExceptionHandler {
context, exception -> println(“Caught $exception”)
}