CoroutineExceptionHandler
- Kotlin course
- Advanced
- Lesson 5/83
- 5 min
Learn error handling with CoroutineExceptionHandler.
What is CoroutineExceptionHandler?
CoroutineExceptionHandler catches uncaught exceptions inside a coroutine. It is a piece of CoroutineContext and is passed to launch as context.
Signature: val handler = CoroutineExceptionHandler { _, throwable -> println(throwable.message) }. The first parameter is the context, the second is the thrown Throwable. The handler is only invoked on root coroutines; it does not work for async. You put recovery logic inside, such as logging, alerts or fallback data.
Using the handler
You pass the handler to launch as context: launch(handler) { throw RuntimeException("Error") }. The thrown exception goes to the handler and appears as the throwable parameter.
Inside the handler you can log the exception, show a user alert or start a fallback flow. After the handler runs, the coroutine is considered crashed; the cancelled state is preserved. So instead of starting a new coroutine inside the handler, log the error and retry from outside for safety.
Practice Define a handler and print
Define val handler = CoroutineExceptionHandler { _, throwable -> println("Error caught") }. Inside main, print println("Ready"). Showing the handler is enough; you do not need to throw.
Starter code
// Handler definition
// write here
fun main() = runBlocking {
}Sample solution
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, throwable ->
println("Error caught")
}
println("Ready")
}Expected output
Ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the handler parameter
val handler = CoroutineExceptionHandler { _, ____ -> println("Error") }
val handler = CoroutineExceptionHandler { _, throwable -> println("Error") }
Explanation: The second parameter is named throwable.
2 What is CoroutineExceptionHandler for?
- Catches uncaught exceptions Correct answer
- Starts a coroutine
- Creates threads
- Picks a dispatcher
Explanation: The handler catches uncaught exceptions.
3 Match the handler parts
| Term | Meaning |
|---|---|
CoroutineExceptionHandler |
Catches exception |
throwable |
Thrown exception |
context |
First parameter |
launch |
Takes context |