开发者

Throwing an AggregateException in my own code

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 exceptions thrown from a part of the code. I was hoping to just add the new exceptions to the AggregateException as they arise, but the documentation sort of indicates that it should be constructed with all the Exceptions at once (there is no method to add开发者_运维知识库 an Exception to the object).

And what about creating a new AE every time and just including the previous AE in the list of exceptions? Seems a hokey way to do it.

Any better ideas?


Are you talking about something like this?

var exceptions = new List<Exception>();
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.


The simplest way would be to add the exceptions to a List until you were ready to throw the AggregateException.

It seems strange to me that you would want to return the old exceptions the next time you create an AggregateException, but if you kept your List around, you could just build a new AggregateException from this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜