Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
从种类上分:checked exceptions,unchecked exceptions(runtime exceptions, errors)
Checked exceptions
- use checked exceptions for recoverable conditions
- 通常你可以使用try-catch来处理异常,或者在外层的方法上declare这个异常,propagate it outward, 所以这个异常转移到使用这个方法的人去考虑了
Unchecked exceptions
这种异常不应该,通常也不需要处理。如果程序抛出这种异常,通常无法恢复,继续执行会造成更多伤害,所以会给出合适的出错原因并且终止当前线程。
- runtime exceptions
- 遇到runtime exceptions表明precondition violations - 未能遵守API的相关协定。比如,array的access超出了允许的范围,ArrayIndexOutOfBoundsException就是precondition violation的一种。
- errors
- error通常是JVM用来表示resource deficiencies,invariant failures, 或者其他使执行不能继续的情况。所以通常不要去implement any new Error subclasses. all of the unchekced throwables you implement should subclass RuntimeException.
异常也是一个object,所以可以定义方法。通常这种方法的作用是为了提供产生异常情况的的额外信息。如果缺少这种方法,往往也只能求助于异常的to string表达,然而to String的implementation也不会包括什么有用的信息。
由于 checked exceptions通常用来表示可以恢复的状况,在exception上提供方法来呈现更多的信息,有利于caller来做恢复。比如,当你尝试买东西的时候失败了,因为卡里没钱了,这时候这个方法如果能返回差多少钱的信息给消费者,这样有利于接下里的处理。