在我自己的代码中抛出一个AggregateException [英] Throwing an AggregateException in my own code

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

问题描述

如何收集例外并将其放入 AggregateException 重新抛出?

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

对于我的具体代码,我有一个循环,并且会从代码的一部分抛出零个或多个异常。我希望在它们出现时将新的异常添加到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,只是将以前的AE包括在异常列表中呢?似乎是一个hokey的方式来做。

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.

任何更好的想法?

推荐答案

你正在谈论这样的东西?

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.

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

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