how do I log crash to the server without try-catch block?

52 views Asked by At

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

1

There are 1 answers

0
Steyrix On

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 ArrayIndexOutOfBoundException is pointless, since you can avoid exception by rewriting while-loop condition as while(i < range.size() - 1) or not using while-loop at all and using for.