Should try…catch go inside or outside a loop?

后端 未结 21 1931
眼角桃花
眼角桃花 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 17:54

    While performance might be the same and what "looks" better is very subjective, there is still a pretty big difference in functionality. Take the following example:

    Integer j = 0;
        try {
            while (true) {
                ++j;
    
                if (j == 20) { throw new Exception(); }
                if (j%4 == 0) { System.out.println(j); }
                if (j == 40) { break; }
            }
        } catch (Exception e) {
            System.out.println("in catch block");
        }
    

    The while loop is inside the try catch block, the variable 'j' is incremented until it hits 40, printed out when j mod 4 is zero and an exception is thrown when j hits 20.

    Before any details, here the other example:

    Integer i = 0;
        while (true) {
            try {
                ++i;
    
                if (i == 20) { throw new Exception(); }
                if (i%4 == 0) { System.out.println(i); }
                if (i == 40) { break; }
    
            } catch (Exception e) { System.out.println("in catch block"); }
        }
    

    Same logic as above, only difference is that the try/catch block is now inside the while loop.

    Here comes the output (while in try/catch):

    4
    8
    12 
    16
    in catch block
    

    And the other output (try/catch in while):

    4
    8
    12
    16
    in catch block
    24
    28
    32
    36
    40
    

    There you have quite a significant difference:

    while in try/catch breaks out of the loop

    try/catch in while keeps the loop active

提交回复
热议问题