*Proposal*: An elvis type operator that catches ex...
# language-proposals
e
Proposal: An elvis type operator that catches exceptions. Example and proposed syntax:
Copy code
exampleString.toInt() !: -1
👀 1
Oh, well the reply got deleted, but here are my answers. "Should it catch Throwable or Exception?": I'd say Exception since Error isn't usually going to be a case where you just fallback to some other behavior and move on. "catching cancellations might be unexpected/non-obvious": Maybe? idk as much about coroutines, but it seems like it would at least be a well-defined behavior, if not always the obvious one. But if you are following a call to a coroutine with a !: I feel like you'd have to had put some thought into what that can entail. Plus I could easily see that being the desired behavior, "if the coroutine cancels, default to this value".
e
Checked exceptions on JVM are broken beyond repair. Do not use them to drive the logic of your code and you will not need an operator. Treat all exceptions as failures that are only handled at the top level in your app, handle exceptions locally only when working with legacy exception-(ab)using libs.
âž• 8
l
Still, exceptions are the most practical way to deal with structured concurrency when you want to cancel no longer needed tasks because of a failure AFAIK.
f
We had a long winded discussion around this somewhere not long ago. Nothing is wrong with exceptions nor checked exceptions but ergonomics are bad. Kotlin has no alternative solution and shouldn't throw with stones here.
c
@elizarov so the kotlin way is to use a result type? never throw exceptions?
d
I think that regular exceptions are fine until you try to use it for control flow (for example like python does with iterators: python iterator doesn't have
hasNext
method,
next
just throws exception and
for
loop catches it, which is awful IMO). Exception is exceptional situation.
👌 3
f
Using exceptions/result for control flow is not per se wrong. It is expensive in most languages because stack trace construction and stack unwinding, this is true for Kotlin/JVM and why we have the "exceptions for exceptions" rule. https://kotlinlang.slack.com/archives/C0B9K7EP2/p1603735245126100?thread_ts=1603720144.099700&cid=C0B9K7EP2 this is a direct link into a very long thread where we discussed pretty much the same. The direct link starts with my comment where I tried to illustrate that there actually isn't much of a difference between Rust's
Result
and checked exceptions.