Ser*_*pin 6 kotlin kotlin-coroutines
考虑这样的代码:
\ncoroutineScope {\n try {\n supervisorScope { launch { error("") } }\n } catch (t: Throwable) {\n println("logs and stuff")\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n运行此代码,我希望logs and stuff在输出中看到,但它会将异常一直传播到原始范围,除非已CoroutineExceptionHandler安装,否则它将失败。
问题是:这是设计使然,还是一个错误(如果是这样,\xe2\x80\x94 将打开一个问题)?
\nPS 切换到内部coroutineScope“修复”问题
coroutineScope {\n try {\n coroutineScope { launch { error("") } }\n } catch (t: Throwable) {\n println("now you\'ll see it")\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n
这是按设计工作的。
第一个示例中的错误实际上并未传播到外部范围。相反,错误由主管作用域捕获,并且外部作用域继续正常运行而不会遇到错误。这是主管作用域的预期行为,也是该catch块永远不会运行的原因。
您可以通过在 catch 块后添加更多代码来演示这一点。外部作用域内但在 catch 块之后的代码将继续正常运行,表明外部作用域中没有遇到错误。
suspend fun main(): Unit = coroutineScope {
try {
supervisorScope { launch { error("") } }
} catch (t: Throwable) {
println("you won't see this")
}
println("but you will see this")
}
Run Code Online (Sandbox Code Playgroud)
由于错误不会传播到主管范围之外,因此它会被传递到该范围的未捕获异常处理程序。这就是为什么您会看到错误被打印到标准错误流。它并不表明应用程序崩溃了。
| 归档时间: |
|
| 查看次数: |
370 次 |
| 最近记录: |