https://kotlinlang.org logo
#announcements
Title
# announcements
p

Pawel

03/16/2020, 6:19 PM
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

SackCastellon

03/16/2020, 6:25 PM
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

Pawel

03/16/2020, 6:26 PM
Good questions, both can throw, and I don't care if
a
is null in
catch
block
s

SackCastellon

03/16/2020, 6:43 PM
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