Kotlin – exception后继续协程

我的问题

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协同程序只允许在设计的暂停点暂停执行代码(使用暂停function)。 协程并不是一般的goto-like控制结构。 恰恰相反,这是一个非常好的约束和严格检查的控制流概念,尽管事实上可以暂停代码的执行并在稍后恢复,但确保您不会破坏代码的顺序执行错觉。

Kotlin协程实现一次性延续 ,一旦代码块被暂停,它只能被恢复一次,继续遵循常规的顺序执行逻辑,例如,如果代码抛出一个exception,你仍然可以挂起id,但是你只能恢复它继续做下去(处理这个例外)。

对于某些方法1, someMethod2someMethod3必须suspend fun 。 然后,您只需要在控制器中捕获exception并恢复协程。