捕获在foreach条件中引发的异常 [英] Catch exception thrown in foreach condition

查看:1300
本文介绍了捕获在foreach条件中引发的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 foreach 循环,该循环在foreach本身的情况下在循环期间中断。有没有办法尝试捕获引发异常的项目,然后继续循环?

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?

这将运行

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

这根本不会运行,因为例外情况是在foreach条件下

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
   }
}

我知道有些人会问这是怎么回事,所以这是这样:
异常 PrincipalOperationException 被抛出,因为 GroupPrincipal (蜜蜂)中找不到> Principal (在我的示例中为b)。

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).

编辑:我在下面添加了代码。我还发现一个组成员指向一个不再存在的域。我很容易通过删除成员来解决此问题,但我的问题仍然存在。

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
}


推荐答案

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

Almost the same as the answer from @Guillaume, but "I like mine better":

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;
            }
        }
    }
}

这篇关于捕获在foreach条件中引发的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆