Sobes.tech
Junior — Middle

Hoe implementeer je foutafhandeling in asynchrone coroutines?

sobes.tech AI

Antwoord van AI

In Kotlin kunnen uitzonderingen in coroutines worden afgehandeld met try-catch-blokken binnen de coroutine zelf of door gebruik te maken van speciale constructies zoals CoroutineExceptionHandler.

Voorbeeld met try-catch binnen de coroutine:

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

Als de coroutine wordt gestart via launch, worden onhandelde uitzonderingen doorgegeven aan CoroutineExceptionHandler:

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

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

Op deze manier kunt u fouten flexibel beheren in asynchrone code.