Junior — Middle
Hoe wordt foutafhandeling uitgevoerd binnen CoroutineScope in Kotlin?
sobes.tech AI
Antwoord van AI
Foutafhandeling in CoroutineScope in Kotlin wordt gedaan met behulp van uitzonderingsmechanismen en speciale foutverwerkers.
Belangrijkste methoden:
- try-catch binnen de coroutine Je kunt de coroutine-code in een try-catch-blok plaatsen voor lokale foutafhandeling.
launch {
try {
// code die een uitzondering kan veroorzaken
} catch (e: Exception) {
// foutafhandeling
}
}
- CoroutineExceptionHandler Dit is een speciale handler die je aan de coroutine-tekst kunt toevoegen voor globale afhandeling van onopgevangen uitzonderingen in coroutines gestart via launch (maar niet via async).
val handler = CoroutineExceptionHandler { _, exception ->
println("Gevangen $exception")
}
val scope = CoroutineScope(Dispatchers.Main + handler)
scope.launch {
throw RuntimeException("Fout")
}
- Foutafhandeling in async Bij async worden uitzonderingen niet meteen gegooid, maar bij het aanroepen van await(), dus moet de foutafhandeling daar plaatsvinden.
val deferred = async {
throw RuntimeException("Fout")
}
try {
deferred.await()
} catch (e: Exception) {
// afhandeling
}
Dus, de keuze van de methode hangt af van het type coroutine en het gewenste foutafhandelingsniveau.