0Pricing
Kotlin Academy · Lesson

CoroutineExceptionHandler: Global Uncaught Handler

Install a CoroutineExceptionHandler to log or recover from unhandled exceptions.

What Is CoroutineExceptionHandler?

CoroutineExceptionHandler is a context element that handles uncaught exceptions from coroutines that do not have a catch handler. It acts as a last resort.

import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { context, exception ->
    println("Caught unhandled: ${exception.message}")
}
fun main() = runBlocking {
    val scope = CoroutineScope(Dispatchers.Default + handler)
    scope.launch { throw RuntimeException("oops") }
    delay(100)
}

Only for Root Coroutines

CoroutineExceptionHandler only catches exceptions from root coroutines (launched directly on a scope). Child coroutines propagate to their parent, not the handler.

import kotlinx.coroutines.*
val handler = CoroutineExceptionHandler { _, e -> println("Handler: ${e.message}") }
fun main() = runBlocking {
    // Root coroutine — handler fires:
    CoroutineScope(handler).launch {
        throw RuntimeException("root error")
    }
    delay(100)
    // NOT handler (child of coroutineScope):
    // launch { launch { throw RuntimeException() } }
}

All lessons in this course

  1. SupervisorJob vs Job: Failure Isolation
  2. CoroutineExceptionHandler: Global Uncaught Handler
  3. async/await Exception Propagation
  4. Designing Resilient Coroutine Architectures
← Back to Kotlin Academy