Is there some sugar for `try catch` which doesn’t ...
# coroutines
u
Is there some sugar for
try catch
which doesn’t catch
CancellationException
? or should I not care to rethrow that?
j
There is no sugar that I know of. You should indeed care and rethrow
CancellationException
if you have a
catch
that is too wide. But you should try to limit your
catch
in the first place. Try not to catch
Exception
, focus on the expected exceptions.
u
agreed, but, I'd rather catch too wide than forget to catch something and crash the app 😔 oh well, exceptions as control flow
j
It depends at which level you're reasoning. At the highest levels, you can have some catch-alls where you carefully consider what you can do with such errors. At lower levels, it's likely best to only catch what you know, and let other exceptions bubble up to the global handler(s)
u
right
thanks!
s
Java has borked up its "exception" facility a bit. They have been treated as return values, not for true exceptions. Catching exceptions should be done surgically/specifically, the ones that are expected, and all the others should bubble up, possibly crashing your app. But you see "catch(Throwable t)" everywhere in almost all code bases, so that horse has left the barn. 😁
u
I mean swift does that same. You only see that the method throws, but not what does it throw
n
I tried a couple of sugars over the years but none of them felt particularly nice to use. It should be possible though to write a compiler plugin that replaces, say,
catch (e: AllThrowablesExceptCancellation)
with catch Throwable + throw cancellation. If I had a dollar for every
if (e is CancellationException) throw e
that I wrote, I could fund the development
j
If I had a dollar for every if (e is CancellationException) throw e that I wrote, I could fund the development
Then probably something is wrong with the design of your code. This kind of
catch(e: Exception)
should be rather rare, because it should only happen in the highest levels of the code. The lowest levels should just crash and focus on specific exceptions
u
i think its mostly from not having multicatch for so long
s
There’s also Either.catch in arrow-core which does exactly this. Catches exceptions but lets “fatal” ones be re-thrown. As seen here and this is the list of what’s considered to be fatal (differs depending on platfrom, this is the jvm implementation)