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
Avoid hardcoded wait times  26 May 2018
Guaranteed Progression  19 May 2018
Prefer declarative method names  03 Feb 2018
Using Premeditation  27 Jan 2018
With Relocation  20 Jan 2018
Using Consolidation  13 Jan 2018
Using Semantic Types  06 Jan 2018
Using Extension Methods  30 Dec 2017
Error Methods  25 Nov 2017
Pass implementations, not representations  14 Oct 2017
More smart-code posts »
Archives
October 2009
2009