I have a foreach that breaks during the loop in the condition of the foreach itself. Is there a way to try catch element that throws an exception and then continue the loop?
This will be executed several times until the exception succeeds and then ends.
try { foreach(b in bees) { //exception is in this line string += b; } } catch { //error }
This will not work at all because the exception is in foreach state
foreach(b in bees) { //exception is in this line try { string += b; } catch { //error } }
I know that some of you will ask how this happens, like this: PrincipalOperationException is GroupPrincipal because Principal (b in my example) cannot be found in GroupPrincipal (bees).
Edit: I added the code below. I also found out that one member of the group was pointing to a domain that no longer exists. I easily fixed this by deleting the participant, but my question still remains. How do you handle exceptions that are thrown inside the foreach condition?
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) {
c # foreach exception try-catch
Jonathan eckman
source share