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.