y
07/04/2024, 1:46 PMval thing = try {
doSomethingOrNull()?.doSomethingThatMayThrow()
} catch (_: MyException) {
null
}
if (thing == null) {
// log error and return
}
is there some syntax sugar to "catch" a null value from the try
block, to get rid of the if
block?
(I mean obviously not, but is there some alternative, such that thing
is initialized to not-null and any exceptions are caught?)Thomas Urbanitsch
07/04/2024, 2:10 PMThomas Urbanitsch
07/04/2024, 2:15 PMval thing = runCatching {
doSomethingOrNull()?.doSomethingThatMayThrow()
}.onFailure {
// log error and return
}.getOrNull()
ephemient
07/04/2024, 2:17 PMephemient
07/04/2024, 2:19 PMThomas Urbanitsch
07/04/2024, 2:22 PMval thing = try {
doSomethingOrNull()?.doSomethingThatMayThrow()
} catch (_: MyException) {
// log error and return
}
🤷Daniel Pitts
07/04/2024, 2:28 PM?:
, but as others have said, what you’re actually trying to do might not be the right way to do it.
Why not log and return from the catch itself?ephemient
07/04/2024, 2:29 PMfun logError(e: MyException?) {}
val thing = try {
doSomethingOrNull()?.doSomethingThatMayThrow()
} catch (e: MyException) {
return logError(e)
} ?: return logError(null)
y
07/04/2024, 2:34 PMDaniel Pitts
07/04/2024, 2:38 PMy
07/04/2024, 2:40 PMDaniel Pitts
07/04/2024, 5:28 PMval thing = try {
doSomethingOrNull() ?: run {
logNull()
return
}
} catch (_: MyException) {
handleException()
return
}
Daniel Pitts
07/04/2024, 5:28 PM