Catch Exceptions In Loops

This is related to ThrowDontCatch. While in general it is advisable to throw exceptions but not catch them, here is a case where it makes sense to catch them. Consider a program that recursively scans a directory tree and prints out the names and checksums of all the files that it finds. If reading a particular file throws an exception, the program can either terminate, or it can skip that file and continue processing the other files. In this case the program should log the exception and continue processing the other files. This is because if the program terminates then the user has no good way of getting the checksums of the other files. The pattern here is: an exception in one branch of a loop should not terminate the other branches.

For example, Windows Explorer does not implement this pattern. If you try to delete all the files, and the delete fails on a single file (say, because the file is being used by a process), the batch delete will terminate.

The xUnit framework does implement this pattern. When a single test fails it does not terminate the execution of the other tests. Failure in one branch of the test loop does not terminate all the branches.

Most batch systems, especially when they can take several hours to run, are also designed in this way. A failure in one branch of a loop does not terminate the loop.

--AsimJalis

It really depends what you want. In much UI code, if one pass through the loop is invalid, it means the user did something wrong or the system is in the wrong state, and the results for the other elements will also be invalid. In that case, you want to bail out before you've wasted any more time processing the rest. Note that this assumes the loop doesn't have user-visible side-effects; if it does, you often need to roll back previous results. There ought to be a pattern for SeparateProcessingFromExecution?, but I have no idea what it's called.

Basically, if the events in the loop are independent, catch exceptions inside. If they're dependent, catch exceptions outside, and avoid committing any changes until you're sure they'll all succeed.

- JonathanTang


CategoryException CategoryLoops


EditText of this page (last edited November 3, 2014) or FindPage with title or text search