应该捕获Throwable的哪个子类,而不应该捕获哪个? [英] Which subclass of Throwable should be caught and which shouldn't?

查看:79
本文介绍了应该捕获Throwable的哪个子类,而不应该捕获哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

API文档说从不捕获 Throwable 子类 Error ,这表示异常行为.这是否意味着错误和异常之间的隔离是为了告诉程序员应该捕获哪个子类,而不应该捕获哪个子类?还是还有更多呢?

API doc says never catch Throwable subclass Error which signifies abnormal behavior. Does it implies that the segregation between Error and Exception is to tell programmers that which subclass should be caught and which shouldn't ? Or there is more to it ?

推荐答案

通常, Error 是严重错误(通常在平台本身内 ),您无法做到想像地处理.我唯一关心捕获 Error 的时间是为了记录,然后重新抛出.

In general, Error is something seriously wrong (often within the platform itself) which you could not conceivably handle. The only times I have ever cared about catching Error is in order to log it, following which I then re-throw.

这非常重要,因为很容易使错误(和运行时异常)以永不记录的方式(例如,使用 executorService.submit(Runnable)聆听返回的 Future )

This is vitally important as it is easy to let errors (and runtime exceptions) propagate up the call stack in such a way that they are never logged (e.g. using executorService.submit(Runnable) without listening to the returned Future)

错误通常是这样的:

  • 内存不足
  • 抽象方法错误(例如,针对与版本不同的库运行)
  • 断言(即程序员定义的不变式或不应该发生的事情-大声笑!)
  • out of memory
  • abstract method error (e.g. running against different version of libraries to those built against)
  • Assertions (i.e. programmer-defined invariants, or things that should never happen - lol!)

然后我会说 RuntimeException 通常(尽管并不总是)表示编程错误:

I would then say that RuntimeExceptions are usually (though not always) indicative of programming errors:

  • 不检查null或传入null
  • 传递无效的参数或允许无效的状态
  • 在迭代集合时对其进行修改

我通常也建议对它们进行快速失败,但这是一个灰色区域.也许您在将用户输入传递到服务器之前不检查用户输入-几乎不值得使您的应用崩溃!

I would usually recommend failing-fast on these as well but this is a grey area; perhaps you don't check user input before passing it to the server -hardly worth crashing your app over!

已检查的 Exception (即非运行时)应用于您可能会期望发生并可以合理(或可以想象)在代码中处理的内容.我个人喜欢检查异常,但是由于以相同方式(即,在多个相同的catch块中)处理不同异常类型所涉及的冗长/重复,这些异常繁琐.诸如Scala之类的语言具有更好的catch语法,但是随后它们也删除了 checked 异常的概念!

Checked Exceptions (i.e. non-runtime) should be used for stuff that you could reasonably expect to happen and reasonably (or conceivably) handle in your code. Personally I like checked exceptions but these are rendered cumbersome because of the verbosity/repetition involved in handling distinct exception types in the same manner (i.e. in multiple identical catch blocks). Languages such as Scala have much better catch syntax, but then they removed the concept of checked exceptions as well!

这篇关于应该捕获Throwable的哪个子类,而不应该捕获哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆