Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 959
Crazy DotNet Dev Avatar asked Dec 12 '14 15:12

Crazy DotNet Dev


2 Answers

Becasue exception breaks the code execution, if it is not handled.

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.

like image 112
Tigran Avatar answered Sep 29 '22 00:09

Tigran


You can only throw a single exception, you could however create a bunch of Exceptions and then throw an AggregateException at the end.

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);
}  
like image 42
Ben Robinson Avatar answered Sep 29 '22 00:09

Ben Robinson