在foreach条件下抛出exception

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

这将运行几次,直到exception命中然后结束。

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

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

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

我知道你们中的一些人会问这是怎么回事,所以这就是:Exception PrincipalOperationException被抛出,因为在GroupPrincipal (蜜蜂)中找不到Principal (在我的例子中为b)。

编辑:我添加了以下代码。 我还发现一个组成员指向一个不再存在的域。 我通过删除该成员轻松解决了这个问题,但我的问题仍然存在。 你如何处理在foreach条件下抛出的exception?

 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 TryForEach(this IEnumerable sequence, Action 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; } } } } 

也许你可以尝试创建一个这样的方法:

  public IEnumerable TryForEach(IEnumerable list, Action executeCatch) { if (list == null) { executeCatch(); } IEnumerator enumerator = list.GetEnumerator(); bool success = false; do { try { success = enumerator.MoveNext(); } catch { executeCatch(); success = false; } if (success) { T item = enumerator.Current; yield return item; } } while (success); } 

你可以这样使用它:

  foreach (var bee in TryForEach(bees.GetMembers(), () => { Console.WriteLine("Error!"); })) { } 

我更喜欢使用聚合exception处理程序。 不需要扩展。

.NET Framework 4.6和4.5

AggregateException类 尚未测试代码,但逻辑存在。

  try { foreach (var item in items) { try { //something //your own exception (eg.) if (item < 0x3) throw new ArgumentException(String.Format("value is {0:x}. Elements must be greater than 0x3.")); } catch (Exception regularException) { //predefined exceptions (eg.) throw new ArgumentException(regularException.InnerException.ToString()); } } } catch (AggregateException ae) { ae.Handle((inner) => { //handle your aggregate exceptions Debug.WriteLine(inner.Message); }); }