Asdfasf

Monday, September 22, 2014

EJ-57 Use Exceptions only for Exceptional Conditions

Ref: Effective Java by Joshua Bloch

When used to best advantage,exceptions can improve a program's readability, reliability, and maintainability. When used, inappropriately, they can have the opposite affect.

// Horrible abuse of exceptions. Don't ever do this!
try {
int i = 0;
while(true)
range[i++].climb();
} catch(ArrayIndexOutOfBoundsException e) {
}


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

This principle also has implications for API design. A well-designed API must not force its clients to use exceptions for ordinary control flow.

for (Iterator 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 i = collection.iterator();
while(true) {
Foo foo = i.next();
...
}
} catch (NoSuchElementException e) {
}

No comments: