捕获RichTextBox中的所有异常

时间:2012-11-01 14:54:21

标签: c# winforms exception richtextbox messagebox

我正在尝试将xml文件加载到界面中,并且可能存在许多基于Xml文件中的数据的异常,所以我想立即捕获所有异常。 我得到了大约15个例外,并在RichTextBox或其他内容或MessageBox中显示。

for (int i = 0; i < this.SortedLaneConfigs.Count; i++)
    {
         if(this.SortedLaneConfigs[i].CheckConsistency())
            {
                throw new DataConsistencyException(String.Format("Lane #{0} NOT consistent : {1}", i, e.Message)
            }
    }


if (this.SortedLaneConfigs[i - 1].EndB > this.SortedConfigs[i].BeginB)
    {
        throw new DataConsistencyException(String.Format("Lanes {0} & {1}  overlap", i - 1, i));
    }

    this.SortedLaneConfigs.ForEach(
        laneConfig =>
        {
            if (this.SortedLaneConfigs.FindAll(item => item.Id == laneConfig.Id).Count != 1)
                {
                    new DataConsistencyException(String.Format("Id \"{0}\" present more than once", laneConfig.Id));
                }
        });

我知道,我可以捕获异常并以正常方式在消息框中显示它。

 try
    {
         this.SortedLaneConfigs[i].CheckConsistency();
    }
catch (Exception e)
    {
        MessageBox.Show("Error message below: \n\"" + String.Format("Configs #{0} NOT consistent : {1}", SortedLaneConfigs[i].Id, e.Message) + "\"", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

我用谷歌搜索了它,我找到了这两个链接,link1:http://blogs.elangovanr.com/post/Catch-multiple-Exceptions-together-in-C.aspx link2: Catch multiple exceptions at once?

如何根据这两个链接调整建议的解决方案,以便在RichTextBox或其他内容或messageBox中一次显示所有异常。请帮帮我。

2 个答案:

答案 0 :(得分:1)

如果我错了,请纠正我,但我认为你想要处理可能发生的15种不同的例外情况并一次性在RichTextBox内显示。您可以使用try...catch来捕获它们中的每一个,收集到列表中,然后创建AggregateException。将其传递给RichTextBox并显示所有包含的错误。这是一个代码示例:

private void Form1_Load(System.Object sender, System.EventArgs e)
{
    Dictionary<int, int> dict = GetDictionaryWithData();
    try {
        DoProcessing(dict);
    } catch (AggregateException ex) {
        RichTextBox1.Text = ex.ToString;
    }
}

private Dictionary<int, int> GetDictionaryWithData()
{
    Dictionary<int, int> dict = new Dictionary<int, int>();
    {
        dict.Add(5, 5);
        dict.Add(4, 0);
        dict.Add(3, 0);
        dict.Add(2, 2);
        dict.Add(1, 0);
    }
    return dict;
}

private void DoProcessing(Dictionary<int, int> dict)
{
    List<Exception> exceptions = new List<Exception>();
    for (int i = 0; i <= dict.Count - 1; i++) {
        int key = dict.Keys(i);
        int value = dict.Values(i);
        try {
            int result = key / value;
        } catch (Exception ex) {
            exceptions.Add(ex);
        }
    }
    if (exceptions.Count > 0)
        throw new AggregateException(exceptions);
}

答案 1 :(得分:1)

您可以连接Exception.Message字符串并在任意位置显示它们: 首先在输入方法之前创建StringBuilder实例:

StringBuilder exBuilder = new StringBuilder();

然后执行您的方法并附加异常消息:

try
{
         this.SortedLaneConfigs[i].CheckConsistency();
}
catch (Exception e)
{
        exBuilder.Append("Error message below: \n\"" + String.Format("Configs #{0} NOT consistent : {1}", SortedLaneConfigs[i].Id, e.Message) + "\"");
        exBuilder.Append(Environment.NewLine);
}

完成后,您可以使用exBuilder.ToString();

获取字符串
richTextBox1.Text = exBuilder.ToString();

修改 假设您有一个表格上有RichTextboxButton。如果Button启动您的方法,那么用例可以是这样的:

public partial class Form1 : Form
{
        StringBuilder exBuilder;
        public Form2()
        {
            InitializeComponent();
            exBuilder = new StringBuilder();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            exBuilder.Clear();
            MyMethod();
            //and all your other methods that have exBuilder.Append in their try-catch blocks
            richTextBox1.Text = exBuilder.ToString();
        }

        void MyMethod()
        {
            try
            {
                //you code or whatever
            }
            catch(Exception e)
            {
                exBuilder.Append("Error message below: \n\"" + String.Format("Configs #{0} NOT consistent : {1}", parameter, e.Message) + "\"" + Environment.NewLine);
            }
        }
}