Exception 在Kotlin异常块中,如何实现';其他';(成功)阻止?

Exception 在Kotlin异常块中,如何实现';其他';(成功)阻止?,exception,kotlin,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") 我觉得这本书读

在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")
我觉得这本书读起来很优雅;只有在没有引发异常的情况下,才会到达
else

在科特林如何做到这一点?我应该声明一个局部变量并在块下面检查它吗

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?

我找到了,但这不包括Python中的
else
块功能。

另一种使用
runCatching
的方法是使用
Result
的扩展函数

runCatching {
    someFunc()
}.onFailure { error ->
    handleError(error)
}.onSuccess { someFuncReturnValue ->
    handleSuccess(someFuncReturnValue)
}.getOrDefault(defaultValue)
    .also { finalValue ->
        doFinalStuff(finalValue)
    }

查看文档中的
Result

只需将其作为
try
块的最后一行。如果一切正常,它就会运行ok@Demigod是的,这当然有效,但是:1)异常处理程序还处理从该语句引发的异常,2)它在较大的块中的读取能力不好。(我本来希望从Kotlin文档中漏掉一些简单的东西,但可能当时根本就不在那里。)相应地更新了这个问题如果某个函数()是你自己的,那么可能值得重写它以不使用异常。正如您的代码所显示的那样,处理它们可能是丑陋而冗长的。引用Kotlin链接的文档“注意,除了与java代码交互之外,异常在某些情况下是令人沮丧的,而不是在您自己的代码中抛出异常,考虑使用特殊的返回类型,如选项或两者。”显然,如果您正在与Java代码交互,您没有这样的选择:-)另外,请注意,因为在失败的情况下,“runCatching”是一种“尝试并捕获所有异常”,所以您应该正确处理抛出的异常并将其吞下