Item 59: Avoid unnecessary use of checked exceptions

1954 단어
1.  Unlike return codes, the checked exceptions force the programmer to deal with exceptional conditions, greatly enhancing reliability.
 
2.  An unchecked exception is more appropriate unless the exceptional condition cannot be prevented by proper use of the API and the programmer using the API can take some useful action once confronted with the exception.
 
3.  If the programmer using the API can do no better than the following, an unchecked exception would be more appropriate:
catch(TheCheckedException e) {
  throw new AssertionError(); // Can't happen!
}

//or 

catch(TheCheckedException e) {
  e.printStackTrace(); // Oh well, we lose.
  System.exit(1);
}

 
One example of an exception that fails this test is CloneNotSupportedException. In practice, the catch block almost always has the character of an assertion failure. The checked nature of the exception provides no benefit to the programmer, but it requires effort and complicates programs.
 
4.  One technique for turning a checked exception into an unchecked exception is to break the method that throws the exception into two methods, the first of which returns a boolean that indicates whether the second method can be invoked without exception condition:
if (obj.actionPermitted(args)) {
    obj.action(args);
} else {
    // Handle exceptional condition
    ...
}

 
If an object is to be accessed concurrently without external synchronization or it is subject to externally induced state transitions, this refactoring is inappropriate, as the object’s state may change between the invocations of actionPermitted and action. If a separate actionPermitted method would, of necessity, duplicate the work of the action method, the refactoring may be ruled out by performance concerns.

좋은 웹페이지 즐겨찾기