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() }