开发者

Exception with try-catch and loop in Java

In Java, what is the difference (in term of performance) between:

for (int i = 0; i < count开发者_开发百科; i++) {
    try {
        // code that throws Exception
    } catch (Exception e) {
        e.printStackTrace();
    }
}

and

try {
    for (int i = 0; i < count; i++) {
        // code that throws Exception
    }
} catch (Exception e) {
    e.printStackTrace();
}


In your first version the loop continues if it hits an exception, in the second version the loop continues after the catch block. That is the most important difference of those code snippets.


You can use both, but it all depends on what you want it to do. If you want to continue the execution after the loop finishes once then you do it the first way. If you want to catch an exception then stop executing the loop then you do the second. Performance wise it all depends on what you want to do with it.


The main difference is that in the first snippet of code, even if there is an exception thrown from the try block and it is caught execution of the for loop continues. In the second snippet if an exception is thrown then the for loop is exited. This is because the whole loop is within the try block.


No I'm quite sure there's absolutely no difference from a point of performance here (ignoring the obvious fact about the loop). In both cases you create exactly one entry in the exception table - only the PC values (ie in which range the exception is valid) will be a bit different.

ie if you assume the following is the exception table the only thing that'll change are the x, y and z values..

Exception table:
   from to target type
     x y z <Class java.lang.Exception>


Since you asked about performance in the two versions of code, I am reminded of "Practical Java" (Addison-Wesley 2000) which recommends in Praxis 23: Place try/catch blocks outside of loops.

The reason involves running the code on a JVM with the JIT compiler turned off. In that case, the lack of run-time JIT optimizations results in extra branches in the opcode, leading to reduced performance.

You can read JIT docs of 2014 here: http://www.oracle.com/technetwork/articles/java/architect-evans-pt1-2266278.html


Besides the difference in your logic with the continuing for. It's no noticeable difference between

try {
lots of stuff which might not throw any exception
something that throws exception
} catch (Exception e) {
}

and

lots of stuff which might not throw any exception
try {
something that throws exception
} catch (Exception e) {
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜