Exception handling

Coroutines allow us to write asynchronous code in a sequential manner. This includes exception handling, and we can use the usual try {...} catch {...} block to catch exceptions.

The following example shows how to use it in practice:

fun main(args: Array<String>) = runBlocking<Unit> {
launch {
val result = try {
calculateValue()
} catch (exception: Exception) {
defaultValue
}
println(result)
}
}

val defaultValue = 1

suspend fun calculateValue(): Int = withContext(DefaultDispatcher) { throw Exception() }

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.239.41