I do not understand when to use try-catch , and what is wrong with them ,special this item (57 java-effective) could someone explain this
// Horrible abuse of exceptions. Don't ever do this!
try {
int i = 0;
while(true)
range[i++].climb();
} catch(ArrayIndexOutOfBoundsException e) {
}
for (Mountain m : range)
m.climb();
"Because exceptions are designed for exceptional circumstances, there is little incentive for JVM implementors to make them as fast as explicit tests. Placing code inside a try-catch block inhibit certain optimizations that modern JVM implementations might otherwise perform. The standard idiom for looping through an array doesn’t necessarily result in redundant checks. Modern JVM implementations optimize them away."
Finally, if we cannot use try-catch in each block , how can I log crashes to the server without catch block
You can use try-catch, but you should never abuse it. Avoid exception-driven development.
You should use try-catch only to catch exceptions that you cannot predict as a developer, for example - getting invalid response from server (since you are not responsible for backend, you don't know anything about server's implementation and its' response sending mechanisms).
In the example above, handling
ArrayIndexOutOfBoundExceptionis pointless, since you can avoid exception by rewritingwhile-loop condition aswhile(i < range.size() - 1)or not usingwhile-loop at all and usingfor.