andrid CoroutineScopelaunch 异常处理的示例代码
以下是一个使用launch函数创建协程并处理异常的示例代码:
import kotlinx.coroutines.*
fun main() {
runBlocking {
val job = CoroutineScope(Dispatchers.Default).launch {
try {
// 在这里执行可能会抛出异常的代码
throw RuntimeException("Something went wrong!")
} catch (e: Exception) {
// 捕获并处理异常
println("Caught exception: ${e.message}")
}
}
job.join() // 等待协程执行完毕
println("Coroutine completed")
}
}
在上面的示例中,我们使用runBlocking函数创建了一个协程作用域,并使用launch函数创建了一个协程。在协程的代码块中,我们故意抛出了一个RuntimeException异常。在catch块中,我们捕获并处理了异常,打印了异常的消息。
最后,我们使用join函数等待协程执行完毕,并打印出"Coroutine completed"。
运行上述代码,输出结果如下:
Caught exception: Something went wrong!
Coroutine completed
可以看到,我们成功地捕获并处理了协程中抛出的异常
原文地址: https://www.cveoy.top/t/topic/hKKl 著作权归作者所有。请勿转载和采集!