Is Nesting Try-Catch Statements Within a Loop a Code Smell?

code-qualitycoding-standardscoding-stylejava

I have heard that nesting try-catch statements can often be a code smell, so I'm wondering whether this situation is an exception. If not, what would be some good ways to refactor?

My code looks like the following:

try{
    X x = blah;
    otherStuff;
    for (int i = 0; i < N; i++){
        try{
            String y = Integer.toString(i);
            f(x);
        }
        catch(Exceptions1 e1){
            System.err.println(... + y + ...);
            System.exit(0);
        }
}
catch(Exceptions2 e2){
    ...
}

I'm using Exceptions here to indicate a multi-catch.

e2 is used to catch exceptions thrown by initializing x and doing otherStuff. Ideally, I would have had my try-catch surround only those two lines, but I use x within my loop and wanted to avoid the "unused assignment" warnings caused by initializing to null outside the try-catch.

e1 was not multi-caught with e2 because I want to provide the user with information about iteration details and thus wanted a catch block within the loop.

Best Answer

If the e2 catch is, as you say, only to catch errors in initializing x and doing otherStuff you could extract it to a seperate method. This also seperates the logic nicely and allows you to potentially give a meaningful name to otherStuff.

public X Foo() {
    try{
        X x = blah;
        otherStuff;

        return x;
    }
    catch(Exceptions2 e2){
        ...
    }
}

public void Bar() {    
    X x = Foo();
    for (int i = 0; i < N; i++){
        try{
            String y = Integer.toString(i);
            f(x);
        }
        catch(Exceptions1 e1){
            System.err.println(... + y + ...);
            System.exit(0);
        }
    }
}
Related Topic