vendredi 20 février 2015

Protect a loop with a try/catch block

Let us suppose, I have to loop a lot of collections to retrieve data. I want to enclose each iteration with a try/catch block to avoid premature exit from the loop in case of error. Example:



for(Object o : aCollection) {
try {
// possible exception is thrown here
} catch (Exception e) {
// write log
}
}


However, I have a lot of loops in my code (for, enhanced for, while). Adding a try/catch block is error prone and makes the code less readable.


How can I add such a block to each loop without having to write a lot of boilerplate code?


Is there any pattern/framework that can be used?


How would you solve this problem?


Aucun commentaire:

Enregistrer un commentaire