I remember reading a thread a few months ago about debugging loops in C# and although it was an interesting discussion it didn’t really answer the question “What techniques can you use to debug a long loop?”.

Well it’s something I have done many a time and more oft than not I have just put in a break point, hit F5 over and over again and counted the iterations, waiting for the exception to be thrown.

That’s all well and good if your exception occurs early on in the loop but if you have 1000’s of items to be processed and it happens at the end it can get a little tedious.

Well I had just such a situation last week and an obvious solution presented itself.

Why not just add an index variable, increment it in the loop, run through the code once until the exception is thrown, note the value (x) of the index, add a conditional break-point that checks for index == x , run your code again and voila! It stops every time at the index where the exception occurs for your debugging pleasure.

Some sample code below to illustrate:

int index = 0; try{
List<Person> people = Context.Persons;
foreach (var item in people) { index++; ProcessPerson(item); //<== Something in here causes an exception } } catch (Exception e){
LogException(e); // <== put a break-point here and note the index value
}
Now add your conditional break-point and re-run your code.

conditional-breakpoint

And that’s it. No more pressing F5.

BondiGeek