```val thing = try { doSomethingOrNull()?.doSome...
# getting-started
y
Copy code
val 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?)
t
I don’t think i understand your question, but i do have a feeling that looking into runCatching and the related Result helpers might help you 😅
👎 1
e.g.
Copy code
val thing = runCatching { 
    doSomethingOrNull()?.doSomethingThatMayThrow() 
}.onFailure {
    // log error and return
}.getOrNull()
e
imo runCatching/Result is almost never the right tool. now all throwables are swallowed
I'm not sure what OP is asking for either though
t
agree, but again i think i missed the point of the question (which is already implying that the Exception is not handled at all) @y it might be more clear if you could explain why in your example you don’t just
Copy code
val thing = try {
  doSomethingOrNull()?.doSomethingThatMayThrow()
} catch (_: MyException) {
  // log error and return
}
🤷
👍 1
d
The sugar you’re looking for is Elvis
?:
, 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?
e
Copy code
fun logError(e: MyException?) {}
val thing = try {
    doSomethingOrNull()?.doSomethingThatMayThrow()
} catch (e: MyException) {
    return logError(e)
} ?: return logError(null)
plus1 1
👍 1
y
thanks. in retrospect I admit this was a frivolous request. my original code wasn't even especially verbose.
d
No worries, understanding different ways to do the same thing is good. Sometimes you find out that the more terse approach isn’t more readable.
y
yeah. I wanted to: 1) handle a particular class of exceptions 2) propagate unexpected exceptions 3) handle nulls that's fairly specific and the code should reflect that
👍 1
d
Copy code
val thing = try {
  doSomethingOrNull() ?: run {
    logNull()
    return
  }
} catch (_: MyException) {
  handleException()
  return 
}
is probably how I would write it.
👍 1