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
- SupervisorJob vs Job: Failure Isolation
- CoroutineExceptionHandler: Global Uncaught Handler
- async/await Exception Propagation
- Designing Resilient Coroutine Architectures