Sobes.tech
Junior — Middle

How does error handling inside coroutines using try/catch differ from using CoroutineExceptionHandler?

sobes.tech AI

Answer from AI

In Kotlin coroutines, error handling can be done in two ways: through try/catch inside the coroutine itself and via CoroutineExceptionHandler.

  • try/catch inside the coroutine allows for local catching of exceptions that occur within the coroutine code block. This is convenient when you need to handle the error directly where it might occur.

  • CoroutineExceptionHandler is a global exception handler for coroutines that end with an error and are not caught locally. It only works with coroutines launched with launch (which return a Job), not with async (which return a Deferred), because async requires an explicit call to await to get the result and handle exceptions.

Example:

val handler = CoroutineExceptionHandler { _, exception ->
    println("Caught exception in CoroutineExceptionHandler: $exception")
}

GlobalScope.launch(handler) {
    try {
        // Code that may throw an exception
        throw RuntimeException("Error inside coroutine")
    } catch (e: Exception) {
        println("Caught locally: $e")
    }
}

If an exception is caught in try/catch, CoroutineExceptionHandler will not trigger. If the exception is not handled locally, it will be caught by CoroutineExceptionHandler. Thus, try/catch provides local handling, while CoroutineExceptionHandler offers global handling and is used for logging or other actions for unhandled exceptions.