is `try-catch` idiomatic in Kotlin?
# getting-started
y
is
try-catch
idiomatic in Kotlin?
s
s
@Sam so if I understand the article correctly, it advises to also have to nullable
xOrNull
functions for every
x
function that returns a non-nullable value and throws an exception. But is
try-catch
inside those equivalent or less ideomatic
Copy code
@Throws(...)
fun x(...): X = ...

fun xOrNull(...): X? = try {
  x(...)
} catch (e: Throwable) {
  null
}
than
runCatching
?
Copy code
fun xOrNull(...): X? = runCatching {
  x(...)
}.getOrNull()
s
Unless you specifically need the functionality of
runCatching
, `try`/`catch` is the more idiomatic choice.
runCatching
is intended specifically for those use cases where wrapping an execution into a
Result
enables functional style code that wouldn’t be possible without it. For general use, it actually has some disadvantages, like making it harder to be specific about which errors you want to catch. More info in the KEEP: https://github.com/Kotlin/KEEP/blob/master/proposals/stdlib/result.md
👍 1
y
so what would be the way to deal with a Java function that can throw multiple exceptions, such that each exception is handled differently? there’s no alternative to
try-catch
here, right?
c
No, you can use try-catch, it's the more idiomatic approach.
👍 3