In Java it was considered a bad practice to catch and handle Throwables, because they include unrecoverable Errors. However, runCatching and mapCatching from Kotlin standard library do catch them and wrap them in a Result like any other exception. Is it generally OK to catch Throwables in Kotlin or is Result a special case (and if so, why)?
I found a series of tweets about this topic by Roman Elizarov, Team Lead in Kotlin Language Research:
If you need error logging/handling (usually at the top level), catch
Throwable
. [...] In factcatch(e: Exception)
[is a bad practice]. You either catch an operation-specific exception you need to handle (e.g.IOException
) or all of them (which meansThrowable
). I've never seen a real reason to havecatch(e: Exception)
in your code. It is a bug waiting to hit you.
on distinction between unrecoverable Errors and recoverable Exceptions:
Java wanted to make this distinction in 1996 but failed to adhere to it when the platform grew and scaled. In fact, nowadays it is never possible, in practice, to tell if the problem is recoverable by its class. The distinction in the JVM and the whole naming confusion is just a 25-year-old legacy of the bygone era. No one could have actually predicted back then how it all works out in big systems.
on what to do with Errors:
Log it, notify support, restart the affected operation/subsystem, etc. No reason limiting those actions just to
Exception
subtypes. I've virtually never had issues with logging or otherwise handlingOutOfMemoryError
,StackOverflowError
,AssertionError
, and others (barring fatal bugs in JVM which are rare). The fact [that] they were properly handled in code saved countless hours of support efforts later. In practice [...] OOMs are often caused by bugs in the code that is trying to allocate some very big data structures. When this code crashes with OOM the GC cleans up the memory which lets, at least, your error-handling code to log it properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With