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
Error Methods  25 Nov 2017
Pass implementations, not representations  14 Oct 2017
Avoiding the Singleton Pattern  22 Jul 2017
Implementing the Singleton Pattern  15 Jul 2017
Static Analysis tools for the Win  15 Apr 2017
Exception Logging  19 Jan 2016
On the Merits of Simple Code  28 Nov 2015
Semantic Types  27 Sep 2015
Command Line Processing  21 Sep 2014
Easy String Conversion  24 Aug 2014
More smart-code posts »
Related Pages
October 2009 archive