在foreach条件下抛出异常

Jon*_*man 8 c# foreach exception try-catch

foreach在foreach本身的情况下,我有一个循环在循环中断开.有没有办法try catch抛出异常然后继续循环?

这将运行几次,直到异常命中然后结束.

try {
  foreach(b in bees) { //exception is in this line
     string += b;
  }
} catch {
   //error
}
Run Code Online (Sandbox Code Playgroud)

这根本不会运行,因为异常是在foreach的条件下

foreach(b in bees) { //exception is in this line
   try {
      string += b;
   } catch {
     //error
   }
}
Run Code Online (Sandbox Code Playgroud)

我知道你们中的一些人会问这是怎么回事,所以这就是:PrincipalOperationException抛出异常是因为PrincipalGroupPrincipal(蜜蜂)中找不到(我的例子中的b ).

编辑:我添加了以下代码.我还发现一个组成员指向一个不再存在的域.我通过删除该成员轻松解决了这个问题,但我的问题仍然存在.你如何处理在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
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ers 5

几乎与@Guillaume的答案相同,但"我更喜欢我的":

public static class Extensions
{
    public static IEnumerable<T> TryForEach<T>(this IEnumerable<T> sequence, Action<Exception> handler)
    {
        if (sequence == null)
        {
            throw new ArgumentNullException("sequence");
        }

        if (handler == null)
        {
            throw new ArgumentNullException("handler");
        }

        var mover = sequence.GetEnumerator();
        bool more;
        try
        {
            more = mover.MoveNext();
        }
        catch (Exception e)
        {
            handler(e);
            yield break;
        }

        while (more)
        {
            yield return mover.Current;
            try
            {
                more = mover.MoveNext();
            }
            catch (Exception e)
            {
                handler(e);
                yield break;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)