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

时间:2019-07-24 12:23:07

标签: 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")

我觉得这读起来很优雅; 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?

我发现了Kotlin docs | Migrating from Python | Exceptions,但这并不涵盖Python中的else块功能。

2 个答案:

答案 0 :(得分:1)

我能想到的Kotlin中没有类似的东西。

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")

但是,我建议使用此方法(此处runCatching将在some_func()块内调用try-catch并返回Result,该返回将包含一个异常失败或some_finc()成功的情况下):

    val result = runCatching { some_func() }
    if (result.isSuccess) {
        print("some_func was successful")
        result.getOrNull()    // will return the result of some_func()
    } else {
        result.exceptionOrNull()    // will return thrown exception
    }

    print("this will be printed in any case")

答案 1 :(得分:0)

使用runCatching的另一种方法是使用Result的扩展功能

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

看看Resulthttps://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/index.html

的文档