Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Kotlin Result catch Throwables?

Tags:

kotlin

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)?

like image 810
omnichord Avatar asked Aug 31 '20 02:08

omnichord


1 Answers

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 fact catch(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 means Throwable). I've never seen a real reason to have catch(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 handling OutOfMemoryError, 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.

like image 182
omnichord Avatar answered Oct 27 '22 15:10

omnichord