面试题答案
一键面试在Kotlin协程中,使用async
启动异步任务时,可以通过以下几种方式优雅地捕获和处理异常:
使用try - catch
块
import kotlinx.coroutines.*
fun main() = runBlocking {
try {
val result = async {
// 模拟可能抛出异常的异步任务
if (Math.random() < 0.5) {
throw RuntimeException("任务执行出错")
}
"任务成功结果"
}.await()
println(result)
} catch (e: Exception) {
println("捕获到异常: $e")
}
}
在上述代码中,async
启动的异步任务在try
块内,通过await
获取结果。如果任务在执行过程中抛出异常,await
会将异常抛出,从而被外层的catch
块捕获。
使用CoroutineExceptionHandler
import kotlinx.coroutines.*
val exceptionHandler = CoroutineExceptionHandler { _, exception ->
println("捕获到异常: $exception")
}
fun main() = runBlocking {
val job = GlobalScope.launch(exceptionHandler) {
val result = async {
// 模拟可能抛出异常的异步任务
if (Math.random() < 0.5) {
throw RuntimeException("任务执行出错")
}
"任务成功结果"
}.await()
println(result)
}
job.join()
}
这里创建了一个CoroutineExceptionHandler
,并将其传递给launch
。当async
启动的任务抛出异常时,该异常会被CoroutineExceptionHandler
捕获并处理。这种方式适用于全局处理协程中的异常情况。