Should try...catch go inside or outside a loop?

Posted by mmyers on Stack Overflow See other posts from Stack Overflow or by mmyers
Published on 2008-09-26T19:52:30Z Indexed on 2010/03/11 19:09 UTC
Read the original article Hit count: 181

Filed under:
|
|
|

I have a loop that looks something like this:

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

This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return null if there is an error, so I put the loop inside a try...catch block, like this:

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

But then I also thought of putting the try...catch block inside the loop, like this:

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

So my question is: is there any reason, performance or otherwise, to prefer one over the other?


EDIT: The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer? (EDIT: did it myself, but voted up Jeffrey and Ray's answers)

© Stack Overflow or respective owner

Related posts about java

Related posts about Performance