Checked vs Unchecked Exceptions

区别

检测异常和非检测异常的主要区别,是在编译时是否会进行检查
检测异常必须进行捕获处理或者抛出,否则编译时会报错无法通过。

用法

检测异常也是interface的一部分,是对接口方法的描述:接口调用时可能发生哪些异常,调用方需要关注如何处理这些异常,可以是try catch捕获后处理,也可以往外再抛出由上层调用方处理。检测异常在编程过程中就给出相应的提示,让调用方能够预见和安排如何处理相应的异常

非检测异常主要包括的是编程问题,无法在程序运行过程中恢复或者处理的(因为编程时预见不到)。例如:空制针、内存溢出等,是需要通过修改代码或者调整环境配置来解决的。

非检测异常虽然可以让接口调用起来更干净和方便,不需要麻烦的try catch处理,但这样会使调用方疏于处理应处理的异常。一般来说,不要为了避免麻烦而使用RuntimeException。

Java官方的建议是

  • If a client can reasonably be expected to recover from an exception, make it a checked exception.
    • 如果调用方可以从异常中恢复进行后续处理,那么使用检测异常。
  • If a client cannot do anything to recover from the exception, make it an unchecked exception.
    • 如果调用方不能够从异常中恢复,那么使用非检测异常。

简单概括:需要调用方在运行时关注并处理的异常,声明为检测性异常。

其他参考

https://stackoverflow.com/questions/499437/in-java-when-should-i-create-a-checked-exception-and-when-should-it-be-a-runti

At my last job, we ran into some real issues with Runtime exceptions being forgotten until they showed up in production (on agedwards.com), so we resolved to use checked exceptions exclusively.

在我的上一份工作中,我们遇到了一些真实案例,因为运行时异常被忽略而导致问题在生产环境才出现,所以后来我们只使用检测异常。

https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions

Checked Exceptions should be used for predictable, but unpreventable errors that are reasonable to recover from.

Unchecked Exceptions should be used for everything else.