捕获 foreach 条件中抛出的异常

2024-05-17

我有一个foreach在 foreach 本身的条件下循环期间中断的循环。有没有办法try catch抛出异常然后继续循环的项?

这将运行几次,直到异常发生然后结束。

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

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

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

我知道你们中的一些人会问这是怎么发生的,所以这里是这样的: 例外PrincipalOperationException被抛出是因为Principal(在我的示例中为 b)无法在GroupPrincipal (bees).

Edit:我添加了下面的代码。我还发现一名组成员指向了一个不再存在的域。我通过删除该成员轻松解决了这个问题,但我的问题仍然存在。如何处理 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
}

几乎与@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;
            }
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

捕获 foreach 条件中抛出的异常 的相关文章

随机推荐