Should try…catch go inside or outside a loop?

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

    Performance: as Jeffrey said in his reply, in Java it doesn't make much difference.

    Generally, for readability of the code, your choice of where to catch the exception depends upon whether you want the loop to keep processing or not.

    In your example you returned upon catching an exception. In that case, I'd put the try/catch around the loop. If you simply want to catch a bad value but carry on processing, put it inside.

    The third way: You could always write your own static ParseFloat method and have the exception handling dealt with in that method rather than your loop. Making the exception handling isolated to the loop itself!

    class Parsing
    {
        public static Float MyParseFloat(string inputValue)
        {
            try
            {
                return Float.parseFloat(inputValue);
            }
            catch ( NumberFormatException e )
            {
                return null;
            }
        }
    
        // ....  your code
        for(int i = 0; i < max; i++) 
        {
            String myString = ...;
            Float myNum = Parsing.MyParseFloat(myString);
            if ( myNum == null ) return;
            myFloats[i] = (float) myNum;
        }
    }
    

提交回复
热议问题