Should try…catch go inside or outside a loop?

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

    I'll put my $0.02 in. Sometimes you wind up needing to add a "finally" later on in your code (because who ever writes their code perfectly the first time?). In those cases, suddenly it makes more sense to have the try/catch outside the loop. For example:

    try {
        for(int i = 0; i < max; i++) {
            String myString = ...;
            float myNum = Float.parseFloat(myString);
            dbConnection.update("MY_FLOATS","INDEX",i,"VALUE",myNum);
        }
    } catch (NumberFormatException ex) {
        return null;
    } finally {
        dbConnection.release();  // Always release DB connection, even if transaction fails.
    }
    

    Because if you get an error, or not, you only want to release your database connection (or pick your favorite type of other resource...) once.

提交回复
热议问题