Should try…catch go inside or outside a loop?

后端 未结 21 1960
眼角桃花
眼角桃花 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:44

    That depends on the failure handling. If you just want to skip the error elements, try inside:

    for(int i = 0; i < max; i++) {
        String myString = ...;
        try {
            float myNum = Float.parseFloat(myString);
            myFloats[i] = myNum;
        } catch (NumberFormatException ex) {
            --i;
        }
    }
    

    In any other case i would prefer the try outside. The code is more readable, it is more clean. Maybe it would be better to throw an IllegalArgumentException in the error case instead if returning null.

提交回复
热议问题