`
leonzhx
  • 浏览: 793653 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 57: Use exceptions only for exceptional conditions

阅读更多

1.  Exceptions are, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow. A well-designed API must not force its clients to use exceptions for ordinary control flow.

 

2.  Because exceptions are designed for exceptional circumstances, there is little incentive for JVM implementors to make them as fast as explicit tests. Placing code inside a try-catch block inhibits certain optimizations that modern JVM implementations might otherwise perform. The standard idiom for looping through an array doesn't necessarily result in redundant checks. Modern JVM implementations optimize them away.

 

3.  A class with a "state-dependent" method that can be invoked only under certain unpredictable conditions should generally have a separate "state-testing" method indicating whether it is appropriate to invoke the state-dependent method.(Such as next and hasNext method of Iterable.)

 

4.  An alternative to providing a separate state-testing method is to have the state-dependent method return a distinguished value such as null if it is invoked with the object in an inappropriate state.

 

5.  If an object is to be accessed concurrently without external synchronization or is subject to externally induced state transitions, you must use a distinguished return value, as the object’s state could change in the interval between the invocation of a state-testing method and its state-dependent method. Performance concerns may dictate that a distinguished return value be used if a separate state-testing method would duplicate the work of the statedependent method.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics