0

I'm trying to load an xml file into the interface and there may be many exceptions based on data in Xml file, So I want to catch all the exceptions at once. I got around 15 exceptions and display it once RichTextBox or Something else or in a 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));
                }
        });

I know, I can catch exception and display it in a message box, in this normal way.

 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);
    }

I googled it and i found these 2 links, link1:http://blogs.elangovanr.com/post/Catch-multiple-Exceptions-together-in-C.aspx link2: Catch multiple exceptions at once?

How can i adapt the suggested solution from those two links to display all the exceptions at once in RichTextBox or or Something else or in a messageBox. Please help me.

Community
  • 1
  • 1
linguini
  • 1,939
  • 5
  • 49
  • 79
  • Use the RichTextBox.AppendText() method. – Hans Passant Nov 01 '12 at 14:59
  • @ Hans Passant: Could you please show me a snippet that how can i get all the exception at once with RichTextBox.AppendText(). Thank you. – linguini Nov 01 '12 at 15:01
  • Your request makes little sense. Exceptions are not raised all at once. You catch them one at a time. Replace MessageBox.Show with AppendText(). – Hans Passant Nov 01 '12 at 15:09
  • It might be better to use something other than exceptions for this. If these problems in the file are expected to happen, exceptions are going to be about as awkward to use as `goto`s here. – Dan Nov 01 '12 at 16:02
  • @ Dan: certainly, you r correct but this file is already created , i can't change it. That'w why i'm trying to use RTB to append all the excep message as per the solutions given below. – linguini Nov 01 '12 at 16:05

2 Answers2

1

Correct me if I am wrong, but I think you want to handle 15 different exceptions which may possibly happen and show them inside the RichTextBox in one shot. You can use try...catch to catch every one of them, collect into a list, and then create an AggregateException. Pass that to RichTextBox and show all contained errors. Here is a code sample:

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);
}
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
  • @linguini: oops, sorry. Converted to C#. – Victor Zakharov Nov 01 '12 at 15:22
  • I just use try catch for all the exceptions in my calss file and simply use your code in the form to display the exceptions in a Richtextbox, is that correct?? – linguini Nov 01 '12 at 15:25
  • 1
    @linguini: Generally yes. But don't forget to collect all exceptions caught, and throw an aggregate exception when done. This approach also allows you to separate UI from business layer, because DoProcessing does not reference any controls. I consider it to be a bad practice to collect exceptions to `String` as they happen - it adds maintenance effort later, if you decide to process your exceptions differently, for example, log them to database etc. – Victor Zakharov Nov 01 '12 at 15:34
1

You can concatenate the Exception.Message strings and display them wherever you like: First create StringBuilder instance before you enter your method(s):

StringBuilder exBuilder = new StringBuilder();

Then execute your method(s) and append exceptions messages:

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);
}

And after you finish you can get the string with exBuilder.ToString();

richTextBox1.Text = exBuilder.ToString();

EDIT: Suppose that you have a Form which has RichTextbox and Button on it. If the Button initiates your methods, then the use case can be like this:

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);
            }
        }
}
Nikola Davidovic
  • 8,556
  • 1
  • 27
  • 33
  • If i'm not mistake, I have to use `exBuilder.Append` in all the try catch and call it like this `richTextBox1.Text = exBuilder.ToString();` – linguini Nov 01 '12 at 15:18
  • No, you need to append message texts whenever you catch exception and after code finishes, just set the text from the builder in richTextBox1.Text. This way all exceptions will appear at once when you finish. The other solution is what @HansPassant suggested, to append exception message text to the RichTextBox whenever it occurs and they will be visible just after you catch them in your try-catch blocks. – Nikola Davidovic Nov 01 '12 at 15:24
  • Nick: I'm using your code, in the class and in the form, i'm calling it like this, `RichTextBox richTextBox1 = new RichTextBox(); richTextBox1.Text = exBuilder.ToString();` How can i give reference to the èxBuilder`? – linguini Nov 01 '12 at 15:35
  • 1
    @linguini Have you seen the edit? I think it should be more clear to you what to do. – Nikola Davidovic Nov 01 '12 at 16:34