0

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

MWiesner
  • 8,868
  • 11
  • 36
  • 70
العبد
  • 359
  • 5
  • 15
  • 1
    It doesn't say not to use try-catch blocks. It says not to use them in place of "explicit tests". i.e. in this case use traditional for-loop `for (int i = 0; i < range.length; ++i)`. It's not a fantastic example. Essentially what they are getting at is to not use exceptions for normal flow control but only for **exception**al circumstances. – Michael Aug 07 '20 at 11:19
  • I posted an answer with explanation and example, did it help you? – Steyrix Aug 07 '20 at 11:45
  • @Steyrix thank you , but you do not answer all of my questions – العبد Aug 07 '20 at 12:55
  • Do you mean "how can I log crashes to the server without catch block"? Since it is the only question I did not answer – Steyrix Aug 07 '20 at 12:59
  • Please specify your problem, so we will be able to help you – Steyrix Aug 07 '20 at 13:00
  • @Steyrix , item 57 said "Use exceptions only for exceptional conditions" , How can I take a control over all my methods , so every crash is logged to the server – العبد Aug 07 '20 at 14:38
  • It's actually another question, but you CAN use try-catch for this purpose, it is up to you where you want to surround your logic with try-catch. It also dependent on your stack of technologies, logic of crash tracking is different in different technologies (e.g. Android/Spring etc.) – Steyrix Aug 07 '20 at 14:56

1 Answers1

0

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.

Steyrix
  • 2,796
  • 1
  • 9
  • 23