Effective Java 58 Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
2014-04-22 08:46 小郝(Kaibo Hao) 阅读(624) 评论(0) 编辑 收藏 举报Three kinds of throwables
Throwables |
Checked |
Recoverable |
checked exceptions |
Y |
Y |
runtime exceptions |
N |
N |
errors |
N |
N |
Principle
- Use checked exceptions for conditions from which the caller can reasonably be expected to recover.
- 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).
-
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
- 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.
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。