TODO : checked vs unchecked expcetion how detechted in client side.
Rule 1:Use Exception for exceptional conditions only.
a.Exceptions are, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow. Should not be used for working with Logics.
example:
// Horrible abuse of exceptions. Don’t ever do this!
try {
int i = 0;
while(true)
range[i++].climb();
} catch (ArrayIndexOutOfBoundsException e) {
}
Explanation: Tried to utilize JVM internal bound check facility but JVM some time optimizes the code and doesnot do the bound check.
Remember!!! – Prefer Architecture to speed . put measure performance change before putting fimal commit.
b.This principle also has implications for API design. A well-designed API must not force its clients to use exceptions for ordinary control flow.
A “state dependent” method should have a separate “state testing” indication whether it is appropriate to invoke the method
exmplae: Iterator interfacce has state-dependent method next() and corresponding state testing method hasNext() .indicating whether it is appropriate to invoke the state-dependent method.
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) {
}