[Effective Java] Item 58 Use checked exceptions for recoverable conditions and runtime exceptions ..

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来做恢复。比如,当你尝试买东西的时候失败了,因为卡里没钱了,这时候这个方法如果能返回差多少钱的信息给消费者,这样有利于接下里的处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值