kotlin/try-catch
from Kotlinのコルーチン
コードの特定の部分が例外をスローする可能性があることがわかっている場合は、そのコードを try-catch ブロックで囲む。
以下は、getTemperature() が例外をスローすると分かっている場合に、その親コルーチンをつくるgetWeatherReport()の呼び出しをtryで囲っている。
code:kotlin
import kotlinx.coroutines.*
fun main() {
runBlocking {
println("Weather forecast")
try {
println(getWeatherReport())
} catch (e: AssertionError) {
println("Caught exception in runBlocking(): $e")
println("Report unavailable at this time")
}
println("Have a good day!")
}
}
suspend fun getWeatherReport() = coroutineScope {
val forecast = async { getForecast() }
val temperature = async { getTemperature() }
"${forecast.await()} ${temperature.await()}"
}
suspend fun getForecast(): String {
delay(1000)
return "Sunny"
}
suspend fun getTemperature(): String {
delay(500)
throw AssertionError("Temperature is invalid")
return "30\u00b0C"
}