Effective Java 58 Use checked exceptions for recoverable conditions and runtime exceptions for progr...

Three kinds of throwables

Throwables

Checked

Recoverable

checked exceptions

Y

Y

runtime exceptions

N

N

errors

N

N

Principle

  1. Use checked exceptions for conditions from which the caller can reasonably be expected to recover.
  2. Code that parses the string representation of an exception is likely to be non portable and fragile. Since the toString() implementation may change from release to release (Item 10).
  3. Provide methods that furnish information that could help the caller to recover.

    For example, suppose a checked exception is thrown when an attempt to make a purchase with a gift card fails because the card doesn't have enough money left on it. The exception should provide an accessor method to query the amount of the shortfall, so the amount can be relayed to the shopper  

  4. Use runtime exceptions to indicate programming errors. -The great majority of runtime exceptions indicate precondition violations. (e.g. ArrayIndexOutOfBoundException).

Note

All of the unchecked throwables you implement should subclass RuntimeException directly or indirectly.

Never use behaviorally identical to ordinary checked exceptions (which are subclasses of Exception but not RuntimeException).

Summary

Use checked exceptions for recoverable conditions and runtime exceptions for programming errors. Of course, the situation is not always black and white.  

转载于:https://www.cnblogs.com/haokaibo/p/use-checked-exceptions-for-recoverable-conditions-and-runtime-exceptions-for-programming-errors.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值