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

Michael Myers picture Michael Myers · Sep 26, 2008 · Viewed 101.4k times · Source

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;
}

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?

Answer

Jeffrey L Whitledge picture Jeffrey L Whitledge · Sep 26, 2008

PERFORMANCE:

There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a throw occurs, then the location of the error is compared against the table.

Here's a reference: http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html

The table is described about half-way down.