【问题标题】:Why does my for-each only throw one exception?为什么我的 for-each 只抛出一个异常?
【发布时间】:2014-12-12 15:03:59
【问题描述】:

我有以下代码:

if (errorList != null && errorList.count() > 0)
{
    foreach (var error in errorList)
    {
        throw new Exception(error.PropertyName + " - " error.ErrorMessage, error.EntityValidationFailed);
    }    
}

为什么列表中有多个错误时只抛出一个异常?

【问题讨论】:

  • 这样想 - 你期望执行流程是什么?当第一个异常被抛出时,你期望会发生什么?
  • 异常会停止正常执行。更多信息,请参阅:stackoverflow.com/questions/278466/…
  • @pseudocoder:我要求 OP 一次有效地思考它。
  • @pseudocoder -- à la Socrates criticalthinking.org/pages/socratic-teaching/606
  • @roryap 有趣的链接,经过思考后,我发现 jon 通过建议在引发第一个异常时发生问题来提出“探索”问题。我们现在要采用“Q&Q”格式而不是“Q&A”吗? :P

标签: c# .net asp.net-mvc


【解决方案1】:

因为异常会中断代码执行,如果它没有被处理的话。

所以代码如下:

foreach (var error in errorList)
{
    try 
    {
          throw new Exception(error.PropertyName + " - " error.ErrorMessage, error.EntityValidationFailed);
    }

     catch(...) {}
}   

将引发多个异常,准确地说是errorList.Length 次,将由catch(..) 处理,在循环体内,如果不从catch(..) 重新抛出,将保持在那里。

【讨论】:

    【解决方案2】:

    你只能抛出一个异常,但是你可以创建一堆Exceptions,然后在最后抛出一个AggregateException

    var exceptions = new List<Exception>();
    foreach (var error in errorList)
    {
        exceptions.Add(new Exception(error.PropertyName + " - " error.ErrorMessage, error.EntityValidationFailed));
    }
    
    if(exceptions.Any())
    {
        throw new AggregateException(exceptions);
    }  
    

    【讨论】:

    • 我将变量命名为exceptions ;)
    • 哎呀,胖手指 ;-)
    猜你喜欢
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2010-12-09
    • 1970-01-01
    相关资源
    最近更新 更多