0

我正在对 xml 文件进行反序列化,并且正在尝试使用以下代码捕获所有异常艺术之一,但它仅捕获一个异常。我在这里做错了什么?

代码:

StringBuilder exBuilder;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    var fileName = openFileDialog1.FileName;
    mruOpenRseConfig.AddRecentFile(fileName);
    try
    {
        ConfigDeserialized = MyConfig.DeserializeFromXmlFile(fileName);

    }

    catch (Exception ex)
    {
        if (ex is DataConsistencyException ||
            ex is XmlException)
        {
            exBuilder.Clear();
            exBuilder.Append(ex.Message + Environment.NewLine);

            RichTextBox richTextBox = new RichTextBox();

            richTextBox.Text = exBuilder;
            richTextBox.Dock = DockStyle.Fill;


            Form richMessageBox = new Form
            {
                StartPosition = FormStartPosition.CenterScreen,
                ControlBox = true,
                Text = "Error in File",
                MaximizeBox = false,
                MinimizeBox = false
            };

            richMessageBox.Controls.Add(richTextBox);

            richMessageBox.ShowDialog();
            return;
        }
        throw;
    }
}
4

1 回答 1

5

代码只会抛出一个异常,因此您不能捕获多个异常。

例如:

try
{
    throw new NotSupportedException();
    throw new InvalidOperationException();
}
catch (Exception ex)
{
    //ex will always be NotSupportedException and never InvalidOperationException.
}

你不能让反序列化器处理一个异常然后继续 - 除非它是你自己的 - 在这种情况下,你必须在每一个发生时捕获它们,记录它们然后在之后查看它们,或者如果你想反应,则为每一个引发事件发生在他们身上。

Exceptions are used to break the flow of a program, so when one is thrown it will stop what is doing and break all other execution until handled. Because of this the deserializer has stopped running and aborted as soon as the first exception is throw.

于 2012-11-06T14:56:21.347 回答