This is similar to the other answers, but without the flag, which seems like clutter to me. I don't really understand the question though, so I'm just throwing it out there in case it is useful.
for (Item item : items) {
while (true) {
try {
item.doSomething();
break;
} catch (MyException ex) {
log.warn("Something failed.", ignore);
}
}
}
This approach hinges on the operation of the unlabeled break
statement, which completes abruptly and then exits the enclosing while
statement normally.
Based on subsequent comments, I think there is some confusion about what it means when there are multiple exceptions declared to be thrown by a method.
Each invocation of a method can be terminated by just one exception being thrown. You can't somehow resume invocation where it left off, and handle subsequent exceptions.
So, if a method throws multiple exceptions, catch a common ancestor, and move on. For example, if a method throws java.io.EOFException
or java.nio.channels.ClosedChannelException
, you could simply catch java.io.IOException
since it is a common ancestor. (You could also catch java.lang.Exception
or java.lang.Throwable
for the same reason.) Invoking the method again under the same conditions won't get you any further.
If you want to attempt to invoke the method on each object, even if some fail, use this:
for (Item item : items) {
try {
item.doSomething();
} catch (Exception ignore) { /* This could be any common ancestor. */
log.warn("Something failed.", ex);
}
}