为什么我的 for-each 只抛出一个异常
本文关键字:一个 异常 我的 for-each 为什么 | 更新日期: 2023-09-27 18:34:03
我有以下代码:
if (errorList != null && errorList.count() > 0)
{
foreach (var error in errorList)
{
throw new Exception(error.PropertyName + " - " error.ErrorMessage, error.EntityValidationFailed);
}
}
为什么当列表中有多个错误时,它只抛出一个异常?
如果不
处理异常,则会中断代码执行。
所以代码像:
foreach (var error in errorList)
{
try
{
throw new Exception(error.PropertyName + " - " error.ErrorMessage, error.EntityValidationFailed);
}
catch(...) {}
}
将引发多个异常,准确地说是errorList.Length
次,将由循环体内部的catch(..)
处理,如果不从catch(..)
重新抛出,将保留在那里。
您只能抛出一个异常,但是您可以创建一堆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);
}