[英]Kotlin - Continue Coroutine after Exception
我的问题
是否有可能在异常后继续执行协程?
例
try {
someMethod1()
someMethod2() //Throws an exception!
someMethod3()
} catch(e: Exception) {
//I do not want to call someMethod3 here!
//I want the coroutine to resume after the exception inside of the original block.
} finally {
//I also do not want to call someMethod3 here!
//I want the coroutine to resume after the exception inside of the original block.
}
我不确定这是否可行,但提前谢谢你看看!
简短的回答是,这是不可能的。 更长的答案是:
Kotlin协程允许您仅在设计的挂起点(使用挂起函数) 暂停执行代码。 协同程序不是一般的goto控件构造。 恰恰相反,它是一个非常好的约束和严格检查的控制流概念,它确保您不会打破顺序执行代码的错觉,尽管您可以暂停执行代码并在以后恢复它。
Kotlin协程实现一次性延续 ,一旦代码块暂停,它只能恢复一次继续遵循常规顺序执行逻辑,例如,如果代码抛出异常,你仍然可以暂停id,但你只能恢复它继续做它的目的(处理这个例外)。
对于someMethod1
, someMethod2
和someMethod3
必须是suspend fun
。 然后你需要的只是在控制器中捕获异常并恢复协程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.