Here’s another example of someone working too hard …

try
{
    // Load the XML string into an XmlTextReader
    XDocument xmlFile = XDocument.Parse(inputXmlString);
    string prettyXml = xmlFile.ToString(SaveOptions.None);
    editXml.Text = prettyXml;
    success = true;
}
catch (Exception exception)
{
    if (exception.GetType() == typeof(XmlException))
    {
       ShowMessage("The File is not a valid format. Format should be XML", 
            "Invalid XML File", MessageType.Error, MessageButton.OK);                    
    }
    else
    {
        throw;
    }

    success = false;
}

Here, the developer is trying to only take action on a specific kind of exception. The trick here is that C# includes native support for this kind of thing. The (simpler) code that works as required is this:

try
{
    // Load the XML string into an XmlTextReader
    XDocument xmlFile = XDocument.Parse(inputXmlString);
    string prettyXml = xmlFile.ToString(SaveOptions.None);
    editXml.Text = prettyXml;
    success = true;
}
catch (XmlException exception)
{
    ShowMessage("The File is not a valid format. Format should be XML", 
        "Invalid XML File", MessageType.Error, MessageButton.OK);                    
    success = false;
}

The goal here is to only catch the exception you need, let the others propagate normally.

This kind of error seems to be common with developers with backgrounds involving tools (such as classic Visual Basic) where error handling much coarser than C#.

The key lesson to be learned here isn’t about exception handling, it is this: Habits shouldn’t always be carried forward with you from platform to platform - good practice in one may not be good practice in the next, especially if that practice was to work around limitations in the platform that may no longer exist.

Comments

blog comments powered by Disqus
Next Post
Nobody wants my Code  11 Oct 2009
Prior Post
The Art of Unit Testing  23 Sep 2009
Related Posts
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
When are you done?  18 Apr 2022
Fixing GitHub Authentication  28 Nov 2021
Archives
October 2009
2009