Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Kotlin exception blocks, how does one implement an 'else' (success) block?

In Python, I would do this:

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

I find this very elegant to read; the else block will only be reached if no exception was thrown.

How does one do this in Kotlin? Am I supposed to declare a local variable and check that below the block?

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?

I found Kotlin docs | Migrating from Python | Exceptions, but this does not cover the else block functionality as found in Python.

like image 219
gertvdijk Avatar asked Dec 31 '22 19:12

gertvdijk


1 Answers

Another way to use runCatching is to use the Result's extension functions

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

Take a look at the docs for Result: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/index.html

like image 183
robocab Avatar answered Jan 04 '23 16:01

robocab