Should try…catch go inside or outside a loop?

后端 未结 21 1912
眼角桃花
眼角桃花 2020-11-30 17:33

I have a loop that looks something like this:

for (int i = 0; i < max; i++) {
    String myString = ...;
    float myNum = Float.parseFloat(myString);
            


        
21条回答
  •  伪装坚强ぢ
    2020-11-30 18:00

    Another aspect not mentioned in the above is the fact that every try-catch has some impact on the stack, which can have implications for recursive methods.

    If method "outer()" calls method "inner()" (which may call itself recursively), try to locate the try-catch in method "outer()" if possible. A simple "stack crash" example we use in a performance class fails at about 6,400 frames when the try-catch is in the inner method, and at about 11,600 when it is in the outer method.

    In the real world, this can be an issue if you're using the Composite pattern and have large, complex nested structures.

提交回复
热议问题