在 Python 中,我会这样做:
try:
some_func()
except Exception:
handle_error()
else:
print("some_func was successful")
do_something_else() # exceptions not handled here, deliberately
finally:
print("this will be printed in any case")
Run Code Online (Sandbox Code Playgroud)
我觉得这读起来非常优雅;else只有在没有抛出异常的情况下才会到达该块。
在 Kotlin 中如何做到这一点?我应该声明一个局部变量并在块下面检查它吗?
try {
some_func()
// do_something_else() cannot be put here, because I don't want exceptions
// to be handled the same as for the statement above.
} catch (e: Exception) {
handle_error()
} finally {
// reached in any case
}
// how to handle 'else' elegantly?
Run Code Online (Sandbox Code Playgroud)
我找到了Kotlin 文档 | 从 Python 迁移 | Exceptions,但这不包括elsePython 中的块功能。
另一种使用方法runCatching是使用Result的扩展功能
runCatching {
someFunc()
}.onFailure { error ->
handleError(error)
}.onSuccess { someFuncReturnValue ->
handleSuccess(someFuncReturnValue)
}.getOrDefault(defaultValue)
.also { finalValue ->
doFinalStuff(finalValue)
}
Run Code Online (Sandbox Code Playgroud)
查看以下文档Result:https : //kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/index.html
| 归档时间: |
|
| 查看次数: |
4265 次 |
| 最近记录: |