Table of contents

Exception Handling

This section covers exception handling and cancellation on exceptions. We already know that a cancelled coroutine throws CancellationException in suspension points and that it is ignored by the coroutines’ machinery. Here we look at what happens if an exception is thrown during cancellation or multiple children of the same coroutine throw an exception.

Exception propagation

Coroutine builders come in two flavors: propagating exceptions automatically (launch and actor) or exposing them to users (async and produce). When these builders are used to create a root coroutine, that is not a child of another coroutine, the former builders treat exceptions as uncaught exceptions, similar to Java’s Thread.uncaughtExceptionHandler, while the latter are relying on the user to consume the final exception, for example via await or receive (produce and receive are covered later in Channels section).

It can be demonstrated by a simple example that creates root coroutines using the GlobalScope:

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. val job = GlobalScope.launch { // root coroutine with launch
  4. println("Throwing exception from launch")
  5. throw IndexOutOfBoundsException() // Will be printed to the console by Thread.defaultUncaughtExceptionHandler
  6. }
  7. job.join()
  8. println("Joined failed job")
  9. val deferred = GlobalScope.async { // root coroutine with async
  10. println("Throwing exception from async")
  11. throw ArithmeticException() // Nothing is printed, relying on user to call await
  12. }
  13. try {
  14. deferred.await()
  15. println("Unreached")
  16. } catch (e: ArithmeticException) {
  17. println("Caught ArithmeticException")
  18. }
  19. }

You can get the full code here.

The output of this code is (with debug):

  1. Throwing exception from launch
  2. Exception in thread "DefaultDispatcher-worker-2 @coroutine#2" java.lang.IndexOutOfBoundsException
  3. Joined failed job
  4. Throwing exception from async
  5. Caught ArithmeticException

CoroutineExceptionHandler

It is possible to customize the default behavior of printing uncaught exceptions to the console. CoroutineExceptionHandler context element on a root coroutine can be used as generic catch block for this root coroutine and all its children where custom exception handling may take place. It is similar to Thread.uncaughtExceptionHandler). You cannot recover from the exception in the CoroutineExceptionHandler. The coroutine had already completed with the corresponding exception when the handler is called. Normally, the handler is used to log the exception, show some kind of error message, terminate, and/or restart the application.

On JVM it is possible to redefine global exception handler for all coroutines by registering CoroutineExceptionHandler via ServiceLoader. Global exception handler is similar to Thread.defaultUncaughtExceptionHandler) which is used when no more specific handlers are registered. On Android, uncaughtExceptionPreHandler is installed as a global coroutine exception handler.

CoroutineExceptionHandler is invoked only on uncaught exceptions — exceptions that were not handled in any other way. In particular, all children coroutines (coroutines created in the context of another Job) delegate handling of their exceptions to their parent coroutine, which also delegates to the parent, and so on until the root, so the CoroutineExceptionHandler installed in their context is never used. In addition to that, async builder always catches all exceptions and represents them in the resulting Deferred object, so its CoroutineExceptionHandler has no effect either.

Coroutines running in supervision scope do not propagate exceptions to their parent and are excluded from this rule. A further Supervision section of this document gives more details.

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. //sampleStart
  4. val handler = CoroutineExceptionHandler { _, exception ->
  5. println("CoroutineExceptionHandler got $exception")
  6. }
  7. val job = GlobalScope.launch(handler) { // root coroutine, running in GlobalScope
  8. throw AssertionError()
  9. }
  10. val deferred = GlobalScope.async(handler) { // also root, but async instead of launch
  11. throw ArithmeticException() // Nothing will be printed, relying on user to call deferred.await()
  12. }
  13. joinAll(job, deferred)
  14. //sampleEnd
  15. }

You can get the full code here.

The output of this code is:

  1. CoroutineExceptionHandler got java.lang.AssertionError

Cancellation and exceptions

Cancellation is closely related to exceptions. Coroutines internally use CancellationException for cancellation, these exceptions are ignored by all handlers, so they should be used only as the source of additional debug information, which can be obtained by catch block. When a coroutine is cancelled using Job.cancel, it terminates, but it does not cancel its parent.

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. //sampleStart
  4. val job = launch {
  5. val child = launch {
  6. try {
  7. delay(Long.MAX_VALUE)
  8. } finally {
  9. println("Child is cancelled")
  10. }
  11. }
  12. yield()
  13. println("Cancelling child")
  14. child.cancel()
  15. child.join()
  16. yield()
  17. println("Parent is not cancelled")
  18. }
  19. job.join()
  20. //sampleEnd
  21. }

You can get the full code here.

The output of this code is:

  1. Cancelling child
  2. Child is cancelled
  3. Parent is not cancelled

If a coroutine encounters an exception other than CancellationException, it cancels its parent with that exception. This behaviour cannot be overridden and is used to provide stable coroutines hierarchies for structured concurrency. CoroutineExceptionHandler implementation is not used for child coroutines.

In these examples CoroutineExceptionHandler is always installed to a coroutine that is created in GlobalScope. It does not make sense to install an exception handler to a coroutine that is launched in the scope of the main runBlocking, since the main coroutine is going to be always cancelled when its child completes with exception despite the installed handler.

The original exception is handled by the parent only when all its children terminate, which is demonstrated by the following example.

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. //sampleStart
  4. val handler = CoroutineExceptionHandler { _, exception ->
  5. println("CoroutineExceptionHandler got $exception")
  6. }
  7. val job = GlobalScope.launch(handler) {
  8. launch { // the first child
  9. try {
  10. delay(Long.MAX_VALUE)
  11. } finally {
  12. withContext(NonCancellable) {
  13. println("Children are cancelled, but exception is not handled until all children terminate")
  14. delay(100)
  15. println("The first child finished its non cancellable block")
  16. }
  17. }
  18. }
  19. launch { // the second child
  20. delay(10)
  21. println("Second child throws an exception")
  22. throw ArithmeticException()
  23. }
  24. }
  25. job.join()
  26. //sampleEnd
  27. }

You can get the full code here.

The output of this code is:

  1. Second child throws an exception
  2. Children are cancelled, but exception is not handled until all children terminate
  3. The first child finished its non cancellable block
  4. CoroutineExceptionHandler got java.lang.ArithmeticException

Exceptions aggregation

When multiple children of a coroutine fail with an exception, the general rule is “the first exception wins”, so the first exception gets handled. All additional exceptions that happen after the first one are attached to the first exception as suppressed ones.

  1. import kotlinx.coroutines.*
  2. import java.io.*
  3. fun main() = runBlocking {
  4. val handler = CoroutineExceptionHandler { _, exception ->
  5. println("CoroutineExceptionHandler got $exception with suppressed ${exception.suppressed.contentToString()}")
  6. }
  7. val job = GlobalScope.launch(handler) {
  8. launch {
  9. try {
  10. delay(Long.MAX_VALUE) // it gets cancelled when another sibling fails with IOException
  11. } finally {
  12. throw ArithmeticException() // the second exception
  13. }
  14. }
  15. launch {
  16. delay(100)
  17. throw IOException() // the first exception
  18. }
  19. delay(Long.MAX_VALUE)
  20. }
  21. job.join()
  22. }

You can get the full code here.

Note: This above code will work properly only on JDK7+ that supports suppressed exceptions

The output of this code is:

  1. CoroutineExceptionHandler got java.io.IOException with suppressed [java.lang.ArithmeticException]

Note that this mechanism currently only works on Java version 1.7+. The JS and Native restrictions are temporary and will be lifted in the future.

Cancellation exceptions are transparent and are unwrapped by default:

  1. import kotlinx.coroutines.*
  2. import java.io.*
  3. fun main() = runBlocking {
  4. //sampleStart
  5. val handler = CoroutineExceptionHandler { _, exception ->
  6. println("CoroutineExceptionHandler got $exception")
  7. }
  8. val job = GlobalScope.launch(handler) {
  9. val inner = launch { // all this stack of coroutines will get cancelled
  10. launch {
  11. launch {
  12. throw IOException() // the original exception
  13. }
  14. }
  15. }
  16. try {
  17. inner.join()
  18. } catch (e: CancellationException) {
  19. println("Rethrowing CancellationException with original cause")
  20. throw e // cancellation exception is rethrown, yet the original IOException gets to the handler
  21. }
  22. }
  23. job.join()
  24. //sampleEnd
  25. }

You can get the full code here.

The output of this code is:

  1. Rethrowing CancellationException with original cause
  2. CoroutineExceptionHandler got java.io.IOException

Supervision

As we have studied before, cancellation is a bidirectional relationship propagating through the whole hierarchy of coroutines. Let us take a look at the case when unidirectional cancellation is required.

A good example of such a requirement is a UI component with the job defined in its scope. If any of the UI’s child tasks have failed, it is not always necessary to cancel (effectively kill) the whole UI component, but if UI component is destroyed (and its job is cancelled), then it is necessary to fail all child jobs as their results are no longer needed.

Another example is a server process that spawns multiple child jobs and needs to supervise their execution, tracking their failures and only restarting the failed ones.

Supervision job

The SupervisorJob can be used for these purposes. It is similar to a regular Job with the only exception that cancellation is propagated only downwards. This can easily be demonstrated using the following example:

  1. import kotlinx.coroutines.*
  2. fun main() = runBlocking {
  3. val supervisor = SupervisorJob()
  4. with(CoroutineScope(coroutineContext + supervisor)) {
  5. // launch the first child -- its exception is ignored for this example (don't do this in practice!)
  6. val firstChild = launch(CoroutineExceptionHandler { _, _ -> }) {
  7. println("The first child is failing")
  8. throw AssertionError("The first child is cancelled")
  9. }
  10. // launch the second child
  11. val secondChild = launch {
  12. firstChild.join()
  13. // Cancellation of the first child is not propagated to the second child
  14. println("The first child is cancelled: ${firstChild.isCancelled}, but the second one is still active")
  15. try {
  16. delay(Long.MAX_VALUE)
  17. } finally {
  18. // But cancellation of the supervisor is propagated
  19. println("The second child is cancelled because the supervisor was cancelled")
  20. }
  21. }
  22. // wait until the first child fails & completes
  23. firstChild.join()
  24. println("Cancelling the supervisor")
  25. supervisor.cancel()
  26. secondChild.join()
  27. }
  28. }

You can get the full code here.

The output of this code is:

  1. The first child is failing
  2. The first child is cancelled: true, but the second one is still active
  3. Cancelling the supervisor
  4. The second child is cancelled because the supervisor was cancelled

Supervision scope

Instead of coroutineScope, we can use supervisorScope for scoped concurrency. It propagates the cancellation in one direction only and cancels all its children only if it failed itself. It also waits for all children before completion just like coroutineScope does.

  1. import kotlin.coroutines.*
  2. import kotlinx.coroutines.*
  3. fun main() = runBlocking {
  4. try {
  5. supervisorScope {
  6. val child = launch {
  7. try {
  8. println("The child is sleeping")
  9. delay(Long.MAX_VALUE)
  10. } finally {
  11. println("The child is cancelled")
  12. }
  13. }
  14. // Give our child a chance to execute and print using yield
  15. yield()
  16. println("Throwing an exception from the scope")
  17. throw AssertionError()
  18. }
  19. } catch(e: AssertionError) {
  20. println("Caught an assertion error")
  21. }
  22. }

You can get the full code here.

The output of this code is:

  1. The child is sleeping
  2. Throwing an exception from the scope
  3. The child is cancelled
  4. Caught an assertion error

Exceptions in supervised coroutines

Another crucial difference between regular and supervisor jobs is exception handling. Every child should handle its exceptions by itself via the exception handling mechanism. This difference comes from the fact that child’s failure does not propagate to the parent. It means that coroutines launched directly inside the supervisorScope do use the CoroutineExceptionHandler that is installed in their scope in the same way as root coroutines do (see the CoroutineExceptionHandler section for details).

  1. import kotlin.coroutines.*
  2. import kotlinx.coroutines.*
  3. fun main() = runBlocking {
  4. val handler = CoroutineExceptionHandler { _, exception ->
  5. println("CoroutineExceptionHandler got $exception")
  6. }
  7. supervisorScope {
  8. val child = launch(handler) {
  9. println("The child throws an exception")
  10. throw AssertionError()
  11. }
  12. println("The scope is completing")
  13. }
  14. println("The scope is completed")
  15. }

You can get the full code here.

The output of this code is:

  1. The scope is completing
  2. The child throws an exception
  3. CoroutineExceptionHandler got java.lang.AssertionError
  4. The scope is completed