Throwing an AggregateException in my own code

前端 未结 2 1495
小蘑菇
小蘑菇 2021-02-18 20:24

How should I go about collecting exceptions and putting them into an AggregateException to re-throw?

For my specific code, I have a loop and will have zero or more excep

2条回答
  •  天命终不由人
    2021-02-18 20:49

    Are you talking about something like this?

    var exceptions = new List();
    foreach (var item in items) {
        try {
            DoSomething(item);
    
        } catch (Exception ex) {
            exceptions.Add(ex);
        }
    }
    
    if (exceptions.Count > 0)
        throw new AggregateException(
            "Encountered errors while trying to do something.",
            exceptions
        );
    

    Seems like the most logical way to me.

提交回复
热议问题