Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the placement of a try-catch block affect performance?

Does the placement of a try-catch block affect performance?

EXAMPLE 1: try-catch block inside of the while-loop

while (true) {
    try {
        // ... read from a file
    } catch (EOFException e) {
        break;
    }
}

EXAMPLE 2: try-catch block surrounds the while-loop

try {
    while (true) {
        // ... read from a file
    } 
} catch (EOFException e) {
    // :P
}

Logically, these two examples are equivalent, but which should I prefer?

like image 841
Mr. White Avatar asked Jul 27 '10 03:07

Mr. White


People also ask

Does Try Catch affect performance?

In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.

Do try catch blocks hurt performance C#?

Still, there are some situations where the existence of a try/catch block may prevent optimizations which--but for the try/catch--would have allowed code to run faster. Save this answer. Show activity on this post. Yes, try/catch will "hurt" performance (everything is relative).

Does try catch make code slow?

This answer will obviously vary from compiler to compiler and application to application, but generally yes — “try and catch” is slower than some of the other canonical alternatives to error handling.

Do try catch blocks hurt performance C++?

First and foremost, remember that using try and catch doesn't actually decrease performance unless an exception is thrown. It's "zero cost" exception handling – no instruction related to exception handling is executed until one is thrown.


1 Answers

Should java try blocks be scoped as tightly as possible?

This gives a much better answer than I could. Short of it is, they only add an entry onto a table that's checked when exceptions are thrown, so unless an exception is thrown they don't affect performance. It'd be best to just put it wherever makes it best to try recover, if you can. If not, wherever's useful or makes sense. Though with break outside the loop, I don't think the second is valid anyway.

like image 90
AaronM Avatar answered Oct 25 '22 06:10

AaronM