Sometimes things go wrong when your program runs. Exception handling in coroutines helps you catch and manage these problems smoothly without crashing your app.
Exception handling in coroutines in 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.
try-catch.runBlocking {
try {
val result = riskyOperation()
println("Result: $result")
} catch (e: Exception) {
println("Caught error: ${e.message}")
}
}CoroutineExceptionHandler to catch exceptions from a launch coroutine.val handler = CoroutineExceptionHandler { _, exception -> println("Caught in handler: ${exception.message}") } val job = GlobalScope.launch(handler) { throw RuntimeException("Oops!") } job.join()
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.
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") }
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.
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.