Sobes.tech
Junior — Middle

Kuidas rakendada erandite töötlemist asünkroonsetes korutinates?

sobes.tech AI

Vastus AI-lt

In Kotlin, to handle exceptions in coroutines, you can use try-catch blocks inside the coroutine itself or apply special constructs like CoroutineExceptionHandler.

Example with try-catch inside the coroutine:

launch {
    try {
        val result = someSuspendFunction()
        println(result)
    } catch (e: Exception) {
        println("Error: ${e.message}")
    }
}

If the coroutine is launched via launch, unhandled exceptions are passed to CoroutineExceptionHandler:

val handler = CoroutineExceptionHandler { _, exception ->
    println("Handled exception: ${exception.message}")
}

GlobalScope.launch(handler) {
    throw RuntimeException("Error in coroutine")
}

This way, you can flexibly manage errors in asynchronous code.