我想在某个代码块完成后运行清理代码,而不考虑异常。这不是可关闭的资源,我无法使用 try-with-resources (或 Kotlin 的use)。在 Java 中,我可以执行以下操作:
try {
// ... Run some code
} catch(Exception ex) {
// ... Handle exception
} finally {
// ... Cleanup code
}
Run Code Online (Sandbox Code Playgroud)
以下 Kotlin 代码等效吗?
runCatching {
// ... Run some code
}.also {
// ... Cleanup code
}.onFailure {
// ... Handle exception
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加了样板异常处理 - 我关心的是确保清理代码运行和可维护性。
kotlin ×1