```try { ... } catch { e -> ... }``` `...
# language-proposals
h
Copy code
try {
    ...
} catch { e ->
    ...
}
Copy code
try foo() catch { bar(it) }
Copy code
try foo() catch bar()
or as @Marc Knaup suggested:
Copy code
try foo() else bar()
instead of
catch
in the event you are ignoring the throwable
m
Side note: 2 & 3 would change `e`/`it` from
Exception
to
Throwable
I guess.
h
right, sorry. didn't know what the default type was. But also, why wouldn't `e`/`it` be the precise class of the throwable thrown?
i'll fix that
thoughts otherwise?
m
#2 implies that you can pass a lambda to
catch
. That could imply that you can put any expression to
catch
. Why the
{}
around the 3rd example?
`e`/`it` must have some type at compile-time.
h
ah
m
Copy code
val foo = try something() catch null
😄
It's quite analogous to
if
&
else
Copy code
val foo = if (something()) a else b
It just has an additional condition.
It reads weird though.
catch null
h
the block enclosing the last example just shows how you could enclose multiple lines and also make use of the exception via the lambda format
it's kinda like a reverse of
if else
expression
m
The short form is probably more like
Copy code
val foo = try something() else null
or using lambda
Copy code
val foo = try something() else { it.message }
h
i agree
it'd be like an else block but it also passes the exception as an argument to the lambda function that follows
if you choose to write a lambda
m
Downside of the short form is that you cannot declare what to catch. You'd always catch
Throwable
which isn't good 🤔
h
so then you could also write this?
Copy code
try foo() catch(e: Exception) bar()
essentially a reverse in the formatting of
Copy code
if (someBool) foo() else bar()
m
yeah
maybe
else
could imply
Exception
for cases where you don't care about the kind of exception - but catching
Throwable
is overkill (as it is usually)
h
i like the idea
m
catch
always with type,
else
without and implies
Exception
In the cases where I'd want a super concise style I wouldn't care about the type of exception anyway. Like
val currency = try Currency.getInstance(code) else null
Today I use
Copy code
val currency = runCatching { Currency.getInstance(code) }.getOrNull()
which feels weird
And may catch
Error
🤔
h
yeah, that is definitely not an optimal solution for readability, but understand why you do it.
o
Oh, the famous VB
on error resume next
❤️ 1
h
😅
r
Wow, I was having a deja vu feeling about that RxJava's
onErrorResumeNext
operator, but never managed to understand why. Now I see that was from my childhood ramblings with VB 😁
Taking another thought, that's even more logical as RX originated as a C# library thus having a connection with VB via .Net. Sorry for off-topic, just found it a bit funny :)
d
I like the idea of try else But it might lead to exceptions being overused
l
hmh, I am quite fine with
runCatching
for now 🙂