gpt4 book ai didi

kotlin - 为什么 Kotlin Result 会捕获 Throwables?

转载 作者:行者123 更新时间:2023-12-02 12:01:26 25 4
gpt4 key购买 nike

在 Java 中,捕获和处理 Throwables 被认为是一种不好的做法,因为它们包含不可恢复的错误。但是,来自 Kotlin 标准库的 runCatching 和 mapCatching 确实像任何其他异常一样捕获它们并将它们包装在 Result 中。在 Kotlin 中捕获 Throwables 通常是可以的,还是 Result 是一个特例(如果是,为什么)?

最佳答案

我找到了 a series of tweets Kotlin 语言研究团队负责人 Roman Elizarov 关于这个主题:

If you need error logging/handling (usually at the top level), catchThrowable. [...] In fact catch(e: Exception) [is a bad practice]. You eithercatch an operation-specific exception you need to handle (e.g.IOException) or all of them (which means Throwable). I've never seen areal reason to have catch(e: Exception) in your code. It is a bugwaiting to hit you.


关于不可恢复错误和可恢复异常的区别:

Java wanted to make this distinction in 1996 but failed to adhere toit when the platform grew and scaled. In fact, nowadays it is neverpossible, in practice, to tell if the problem is recoverable by itsclass. The distinction in the JVM and the whole naming confusion isjust a 25-year-old legacy of the bygone era. No one could haveactually predicted back then how it all works out in big systems.


关于如何处理错误:

Log it, notify support, restart the affected operation/subsystem, etc.No reason limiting those actions just to Exception subtypes. I'vevirtually never had issues with logging or otherwise handlingOutOfMemoryError, StackOverflowError, AssertionError, and others(barring fatal bugs in JVM which are rare). The fact [that] they wereproperly handled in code saved countless hours of support effortslater. In practice [...] OOMs are often caused by bugs in the codethat is trying to allocate some very big data structures. When thiscode crashes with OOM the GC cleans up the memory which lets, atleast, your error-handling code to log it properly.

关于kotlin - 为什么 Kotlin Result 会捕获 Throwables?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63663998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com