抛出AggregateException在我自己的code [英] Throwing an AggregateException in my own code

查看:184
本文介绍了抛出AggregateException在我自己的code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何去收集异常,并把它们放入 AggregateException 重新-throw?

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

有关我的具体code,我有一个循环,将有零个或多个例外情况的code的一部分抛出。我希望在新的例外,因为他们出现的只是添加到AggregateException,但排序的文件表明,它应与所有的例外一次构建(有没有方法来添加一个例外对象)。

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).

和什么有关创建新的AE每一次,只是包括例外列表中的previous AE?似乎是一个做作的方式来做到这一点。

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.

更好的想法?

推荐答案

你说的是这样的事情?

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.

这篇关于抛出AggregateException在我自己的code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆