在 Kotlin 异常块中,如何实现“else”(成功)块?

ger*_*ijk 2 exception kotlin

在 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 中的块功能。

rob*_*cab 6

另一种使用方法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

  • 另请注意,因为“runCatching”是失败情况下的“尝试并捕获所有异常”,所以您应该正确处理抛出的异常,并且只需吞掉它们即可 (3认同)