Skip to content

Latest commit

 

History

History
139 lines (111 loc) · 7.57 KB

File metadata and controls

139 lines (111 loc) · 7.57 KB

Java Exceptions

Introduction

某类异常代表什么?

Categories

分类

  • Error 系统异常 : 不应捕获
  • Exception : 可以捕获
  • Throwable : 包含 Error 和 Exception, 因此不应捕获它
  • RuntimeException : 非受查异常

Unchecked Exception

非受查异常

"If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?"

  • Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way.
  • Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

Here's the bottom line guideline :

  • 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.
  • Checked exceptions are not really exceptions.
    • The thing about checked exceptions is that they are not really exceptions by the usual understanding of the concept.
    • Instead, they are API alternative return values.

Class Hierarchy

什么时候该用哪个异常类?

  • Java 异常类继承层次 ( 类父子关系 )

References

Throwable

Differ Throwable and Exception

Error

Exception

Checked Exception Arguement

相关争论

自己的想法

  • Fail Fast 策略是合理的
    • 把 Checked Expcetion 包装成 RuntimeException 抛出去就完事了…
    • 像是在 Java 里给方法加 lombok 的注解 @SneakyThrow
  • 如果你还想着使用 Checked Exception, 或许可以这么做?
    • 改为抛出其它 RuntimeException 的子类 ( 自行定义, 以区分各种意外情况 )
    • 然后把会抛出的异常, 添加到 JavaDoc @throw 的注释说明中 ( 关心异常的调用方, 自行决定处理或忽略异常 )