How to Handle Exception in Coroutine in Kotlin
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.
import kotlinx.coroutines.* fun main() = runBlocking { launch { throw RuntimeException("Error in coroutine") } println("This line may not run") }
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.
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") }
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.