简体   繁体   English

为什么我的for-each只抛出一个例外?

[英]Why does my for-each only throw one exception?

I have the following code: 我有以下代码:

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

Why does it only throw one exception when multiple errors are in the list? 为什么在列表中出现多个错误时只抛出一个异常?

Becasue exception breaks the code execution , if it is not handled. 如果没有处理,则Becasue异常会中断代码执行

So the code like: 所以代码如下:

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

     catch(...) {}
}   

will raise multiple exceptions, to be precise errorList.Length times, which will be handled by catch(..) , inside the loop body, if not re-thrown from the catch(..) , will remain there. 将引发多个异常,准确地说是errorList.Length次,这将由catch(..)处理, 如果没有catch(..) 重新抛出 ,将保留在循环体内。

You can only throw a single exception, you could however create a bunch of Exceptions and then throw an AggregateException at the end. 你只能抛出一个异常,然而你可以创建一堆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);
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM