I have a foreach loop that breaks during the loop in the condition of the foreach itself. Is there a way to try catch the item that throws the exception and then continue the loop?
This will run a few times until the exception hits and then end.
try {
foreach(b in bees) { //exception is in this line
string += b;
}
} catch {
//error
}
This will not run at all because the exception is in the condition of the foreach
foreach(b in bees) { //exception is in this line
try {
string += b;
} catch {
//error
}
}
I know some of you are going to ask how this is happening so here is this:
Exception PrincipalOperationException is being thrown because a Principal (b in my example) cannot be found in GroupPrincipal (bees).
Edit: I added the code below. I also figured out that one group member was pointing to a domain that no longer exists. I easily fixed this by deleting the member but my question still stands. How do you handle exceptions that are thrown inside the condition of a foreach?
PrincipalContext ctx = new PrincipalContext(ContextType.domain);
GroupPrincipal gp1 = GroupPrincipal.FindByIdentity(ctx, "gp1");
GroupPrincipal gp2 = GroupPrincipal.FindByIdentity(ctx, "gp2");
var principals = gp1.Members.Union(gp2.Members);
foreach(Principal principal in principals) { //error is here
//do stuff
}
beesobject. For debugging purposes, try to "manually" enumeratebees. It's some sort ofIEnumerable<T>orIEnumerable. Manually do.MoveFirst()and see if you get the exception right away. - John SaundersGroupPrincipalyou mean? Because I cannot see that it is even enumerable.). Maybe we can find a more "domain specific" solution for your problem then, which could ultimately be easier than the "generic" case. - Christian.K