0
0
KotlinDebug / FixBeginner · 4 min read

How to Handle Exception in Coroutine in Kotlin

In Kotlin, you handle exceptions in coroutines by using try-catch blocks inside the coroutine or by attaching a CoroutineExceptionHandler to the coroutine context. For structured concurrency, you can also use supervisorScope to isolate failures without cancelling sibling coroutines.
🔍

Why This Happens

When an exception occurs inside a coroutine and is not caught, it can crash the coroutine and cancel its parent scope, leading to unexpected program termination or silent failures.

This happens because coroutines follow structured concurrency, where exceptions propagate up the coroutine hierarchy unless handled.

kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        throw RuntimeException("Error in coroutine")
    }
    println("This line may not run")
}
Output
Exception in thread "main" java.lang.RuntimeException: Error in coroutine at ... (stack trace) CoroutineExceptionHandler is not used, so exception crashes the program.
🔧

The Fix

Wrap the coroutine code that may throw an exception inside a try-catch block to catch and handle exceptions locally.

Alternatively, use CoroutineExceptionHandler to handle uncaught exceptions globally in the coroutine context.

kotlin
import kotlinx.coroutines.*

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

    launch(handler) {
        try {
            throw RuntimeException("Error in coroutine")
        } catch (e: Exception) {
            println("Handled inside coroutine: ${e.message}")
        }
    }

    launch(handler) {
        throw RuntimeException("Unhandled error")
    }

    delay(100) // Wait for coroutines
    println("Program continues")
}
Output
Handled inside coroutine: Error in coroutine Caught exception: Unhandled error Program continues
🛡️

Prevention

Always anticipate exceptions in coroutines by using try-catch blocks or CoroutineExceptionHandler.

Use supervisorScope when you want child coroutines to fail independently without cancelling siblings.

Keep coroutine exception handling close to where the coroutine is launched to avoid silent failures.

⚠️

Related Errors

CancellationException: This exception is thrown when a coroutine is cancelled. It is usually not caught because it is used to stop coroutines gracefully.

Unhandled exception crashes: If exceptions are not handled, they can crash the whole application or cancel parent coroutines unexpectedly.

Key Takeaways

Use try-catch inside coroutines to handle exceptions locally.
Attach CoroutineExceptionHandler to catch uncaught exceptions globally.
Use supervisorScope to isolate failures among child coroutines.
Never ignore exceptions in coroutines to prevent crashes.
Place exception handling close to coroutine launch for clarity.