When used to best advantage,exceptions can improve a program's readability, reliability, and maintainability. When used, inappropriately, they can have the opposite affect.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
Post a Comment