A method should throw only a throws exception if it can create reasonable guarantees surrounding the state of the object, any parameters passed to the method, and any other objects that the method acts on. For example, a method that is supposed to extract from the collection an element that is supposed to be contained in it may throws exception if the element that was supposed to exist in the collection does not work. The caller who catches this exception should expect that the collection does not contain the item.
Note that while Java allows checked exceptions to create bubbles through a method declared to exclude exceptions from the corresponding types, this use should usually be considered an anti-pattern. Imagine, for example, that some LookAtSky() method is declared as calling a FullMoonException , and is expected to throw it when the moon is full; Suppose further that LookAtSky() throws ExamineJupiter() , which is also declared as throws FullMoonException . If a FullMoonException was ExamineJupiter() , and if LookAtSky() did not catch it and did not FullMoonException it or FullMoonException it into any other type of exception, then the code that called LookAtSky would suggest an exception, the result was that the Earth moon is full; he would not know that one of the moons of Jupiter could be the culprit.
Exceptions that the caller can expect to handle (including essentially all checked exceptions) should be allowed to leak through the method if that exception means the same for the calling method as it matters to the called method. If the code calls a method that is declared as throwing some checked exception, but the caller does not expect it to ever throw that exception (for example, because it considers it to be arguments that have been previously checked), the checked exception must be caught and terminated in some uncontrolled type of exceptions. If the caller does not expect an exception to be thrown, the caller cannot expect it to have any particular meaning.
supercat Jun 13 '13 at 19:16 2013-06-13 19:16
source share