Hi! I am having logic similar to posted below. Is ...
# announcements
p
Hi! I am having logic similar to posted below. Is there any way to do it better?
Copy code
var a: Int? = null
try {
    a = doSthToGetA()
    useA(a)
} catch(ex: AnyExc) {
    doSthWithA(a)
}
s
What can throw the exception,
doSthToGetA()
,
useA(a)
or both? And does
doSthWithA(a)
expect a nullable type? Do you care about the exception thrown or you just want to know whether an exception was thrown or not?
p
Good questions, both can throw, and I don't care if
a
is null in
catch
block
s
I don't think there is a better way to write that code. At first I thought about using
runCatching
but it doesn't make thinks better.
Copy code
var a: Int? = null
runCatching { a = doSthToGetA().also(::useA) }.onFailure { doSthWithA(a) }
This could be an alternative, however in this case
a
is only assigned if
doSthToGetA
and
useA
don't throw an exception.
👍 1