What is CoroutineExceptionHandler in Kotlin: Explained with Example
CoroutineExceptionHandler in Kotlin is a special handler that catches uncaught exceptions in coroutines. It lets you define how to respond when a coroutine throws an error, helping keep your app stable and avoid crashes.How It Works
Imagine you are running multiple tasks at the same time, like cooking several dishes in a kitchen. If one dish burns, you want to know about it and decide what to do next without ruining the whole meal. CoroutineExceptionHandler works like a smoke alarm for coroutines: it listens for errors that are not caught inside the coroutine itself.
When a coroutine throws an exception that is not handled, this handler catches it and lets you define a custom action, such as logging the error or showing a message. This way, your program can react gracefully instead of crashing unexpectedly.
Example
This example shows how to use CoroutineExceptionHandler to catch an exception thrown inside a coroutine and print a message instead of crashing.
import kotlinx.coroutines.* fun main() = runBlocking { val handler = CoroutineExceptionHandler { _, exception -> println("Caught exception: ${exception.message}") } val job = GlobalScope.launch(handler) { println("Coroutine started") throw RuntimeException("Something went wrong!") } job.join() // Wait for coroutine to finish println("Program continues") }
When to Use
Use CoroutineExceptionHandler when you want to catch and handle exceptions that escape from coroutines running in your app. It is especially useful in long-running or background tasks where you want to avoid crashes and log errors for debugging.
For example, in Android apps, you can use it to catch network errors or unexpected failures in background work and show user-friendly messages or retry logic. It helps keep your app responsive and stable.
Key Points
- Only catches uncaught exceptions: Exceptions handled inside coroutine blocks won't reach this handler.
- Works with CoroutineScope: Attach it to coroutine builders like
launchorGlobalScope. - Helps prevent crashes: Allows graceful error handling and logging.
- Does not handle exceptions in
asynccoroutines: Exceptions inasyncmust be handled byawait().