2

I want to know if I use one or two try catch in a while loop, does this affect the performance or not?

Example code below:

try {
    // some code
    ....

    try {
        // some code
        ...
    } catch(Exception e) {
        if(e is not catchable) {
            //throw it as MyException(e);
        }
    }

    // some code
    ...

} catch(Exception e) {
    if(e is my Exception) {
        then do somthing
        ...
    } else { // is other Exception
        if(e is not catchable) {
            then stop the loop
        }
        // else catch it and continue
    }
}

What about if else if used instead, then which one will be the good idea?

If someone knows pleas tell me does it affect performance or not, if yes then why.

My question maybe asked by someone else before, but I also want to know about if-else if it is better then try-catch.

Edit:

I know if throws Exception then for catching it needs some time, but how about if the program goes whit no Exception jut like:

// some code
        ....
// some code
        ....
// some code
        ....

Thanks!

Razib
  • 10,965
  • 11
  • 53
  • 80
Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68
  • 1
    try blocks themselves doesn't affect performance. Catching exceptions affects performance. So answer depends on frequency of exception throwing inside your loop. – mkrakhin May 05 '15 at 09:58
  • Google is your friend. Please check this one - http://www.precisejava.com/javaperf/j2se/Exceptions.htm – Keerthivasan May 05 '15 at 09:58
  • 1
    Forget performance: this code looks unreadable, which is a much worse thing. Performance improves when hardware gets upgraded; human brain, on the other hand, does not get upgraded (at least not yet), so poor readability remains a problem forever. Testing this code would be a nightmare, too. – Sergey Kalinichenko May 05 '15 at 10:02
  • 3
    Performance aside, catch-all catches (which catch `Exception` rather than specific exceptions) are not recommended. Tailor your code to the actual exceptions it expects. The `if` at the end, for example, should have been covered by two `catch` clauses. – RealSkeptic May 05 '15 at 10:09
  • Also, regarding `if(e is my Exception)` if you plan to do it with `instanceof` it will really degrade performance. If you'll want to leave try/catch in your loop, it's better to use multiple catch blocks. – mkrakhin May 05 '15 at 10:09

1 Answers1

1

Try - catch block doesn't affect performance itself, but the code inside catch block wil be executed every time an exception is throwed, and this could affects permformances.

Nicola
  • 21
  • 3
  • 1
    see the [answer](http://stackoverflow.com/a/8621779/4726707) which talks of overheads in `try-catch` – Blip May 05 '15 at 10:12