0
0
Kotlinprogramming~5 mins

CoroutineExceptionHandler in Kotlin

Choose your learning style9 modes available
Introduction

CoroutineExceptionHandler helps you catch errors in coroutines so your app doesn't crash unexpectedly.

When you want to handle errors from background tasks without stopping the whole app.
When you need to log or show a message if a coroutine fails.
When you want to clean up resources if a coroutine throws an exception.
When you want to keep your app responsive even if some coroutines fail.
Syntax
Kotlin
val handler = CoroutineExceptionHandler { context, exception ->
    // handle the exception here
}

The handler is a lambda that receives the coroutine context and the exception.

You add this handler to a coroutine's context to catch uncaught exceptions.

Examples
This example prints the exception message when the coroutine throws an error.
Kotlin
val handler = CoroutineExceptionHandler { _, exception ->
    println("Caught $exception")
}

GlobalScope.launch(handler) {
    throw RuntimeException("Error!")
}
Here, the handler logs the error message inside a runBlocking coroutine.
Kotlin
val handler = CoroutineExceptionHandler { _, exception ->
    println("Logging error: ${exception.message}")
}

runBlocking {
    launch(handler) {
        throw IllegalStateException("Oops")
    }
}
Sample Program

This program starts a coroutine that throws an exception. The CoroutineExceptionHandler catches it and prints a message. The program continues running after handling the error.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught exception: ${exception.message}")
    }

    val job = launch(handler) {
        println("Coroutine started")
        throw ArithmeticException("Divide by zero")
    }

    job.join()
    println("Coroutine finished")
}
OutputSuccess
Important Notes

CoroutineExceptionHandler only catches exceptions that are not handled inside the coroutine.

It works with launch coroutines but not with async coroutines because async exceptions must be handled when calling await().

Summary

CoroutineExceptionHandler catches uncaught exceptions in coroutines.

Use it to keep your app stable and handle errors gracefully.

Add it to coroutine context when launching coroutines.