Exceptions in Coroutines Flashcards

1
Q

What happened if a coroutine suddenly happened?

A

When a coroutine suddenly fails with an exception, it will propagate said exception up to its parent. Then the parent do the following tasks.

  1. It will cancel the rest of its children
  2. It cancels itself
  3. 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a SupervisorJop in coroutines?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to handle uncaught exception by launch coroutine builder?

A

With launch, exceptions will be thrown as soon as they happen.

scope.launch {
    try {
        codeThatCanThrowExceptions()
    } catch(e: Exception) {
        // Handle exception
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to handle exceptions in async coroutine builder?

A

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
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is CoroutineExceptionHandler?

A

The CoroutineExceptionHandler is an optional element of a CoroutineContext allowing you to handle the uncaught exceptions.

val handler = CoroutineExceptionHandler {
context, exception -> println(“Caught $exception”)
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly