0
0
Kotlinprogramming~5 mins

Exception handling in coroutines in Kotlin

Choose your learning style9 modes available
Introduction

Sometimes things go wrong when your program runs. Exception handling in coroutines helps you catch and manage these problems smoothly without crashing your app.

When you want to catch errors inside a coroutine to prevent your app from stopping.
When you need to handle network failures or timeouts in asynchronous tasks.
When you want to clean up resources or show a message after an error happens in a coroutine.
When you want to log errors from background tasks without crashing the main program.
Syntax
Kotlin
try {
    // coroutine code that might throw an exception
} catch (e: Exception) {
    // handle the exception here
}

You can use try-catch blocks inside coroutines just like in normal code.

For coroutine builders like launch, exceptions are handled differently and may need a CoroutineExceptionHandler.

Examples
This example shows catching an exception inside a coroutine using try-catch.
Kotlin
runBlocking {
    try {
        val result = riskyOperation()
        println("Result: $result")
    } catch (e: Exception) {
        println("Caught error: ${e.message}")
    }
}
This example uses CoroutineExceptionHandler to catch exceptions from a launch coroutine.
Kotlin
val handler = CoroutineExceptionHandler { _, exception ->
    println("Caught in handler: ${exception.message}")
}

val job = GlobalScope.launch(handler) {
    throw RuntimeException("Oops!")
}
job.join()
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("Starting coroutine")
        delay(100)
        throw IllegalArgumentException("Something went wrong")
    }

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

Exceptions in launch coroutines are uncaught by default unless you provide a CoroutineExceptionHandler.

Exceptions in async coroutines are thrown when you call await(), so handle exceptions there.

Always handle exceptions to keep your app stable and user-friendly.

Summary

Use try-catch inside coroutines to catch errors directly.

Use CoroutineExceptionHandler to catch exceptions from launch coroutines.

Handling exceptions keeps your app running smoothly even when errors happen.