zoukankan      html  css  js  c++  java
  • Effective Java 57 Use exceptions only for exceptional conditions

    Principle

    1. Exceptions are, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow.

      // Horrible abuse of exceptions. Don't ever do this!

      try {

      int i = 0;

      while(true)

      range[i++].climb();

      } catch(ArrayIndexOutOfBoundsException e) {

      }  

    2. A well-designed API must not force its clients to use exceptions for ordinary control flow.

      for (Iterator<Foo> i = collection.iterator(); i.hasNext(); ) {

      Foo foo = i.next();

      ...

      }

      If Iterator lacked the hasNext method, clients would be forced to do this instead:

      // Do not use this hideous code for iteration over a collection!

      try {

      Iterator<Foo> i = collection.iterator();

      while(true) {

      Foo foo = i.next();

      ...

      }

      } catch (NoSuchElementException e) {

      }

    3. 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. This technique would not be appropriate for Iterator, as null is a legitimate return value for the next method.
    4. Guidelines to choose between a state-testing method and a distinguished return value.

    Different concerns

    State-testing method

    Distinguished value

    Concurrent Object Accessing without external synchronization/externally induced state transitions

    N

    Y

    Performance concerns

    N

    Y

    Other situations except the conditions above

    Y

    N

    Readability

    Y

    N

    Incorrect use detectable

    Y

    N

    Summary

    Exceptions are designed for use in exceptional conditions. Don't use them for ordinary control flow, and don't write APIs that force others to do so.

  • 相关阅读:
    高级架构进阶之HashMap源码就该这么学
    MySQL底层索引剖析
    一篇文章把本该属于你的源码天赋还给你
    不懂RPC实现原理怎能实现架构梦
    观《亿级流量网站架构核心技术》一书有感
    高效程序员如何优雅落地需求
    职场软技能:开启程序员的“破冰之旅”
    获取ScrollView的onScrollListener
    Android自定义控件之圆形进度条ImageView
    Android之內置、外置SDCard
  • 原文地址:https://www.cnblogs.com/haokaibo/p/use-exceptions-only-for-exceptional-conditions.html
Copyright © 2011-2022 走看看