Why is only one exception thrown for each of them?

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 this cause only one exception when there are several errors in the list?

+6
source share
2 answers

The Becasue exception violates code execution if it is not processed.

So a code like:

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

will throw a few exceptions, or rather errorList.Length times that catch(..) will handle, inside the loop body, if not re-selected from catch(..) , will remain there.

+10
source

You can throw only one exception, however you could throw 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); } 
+9
source

Source: https://habr.com/ru/post/979510/


All Articles