Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exceptions can occur when saving an XDocument?

In my C# application I'm using the following statement:

public void Write(XDocument outputXml, string outputFilename) {
  outputXml.Save(outputFilename);
}

How can I find out which exceptions the Save method might throw? Preferably right in Visual Studio 2012 or alternatively in the MSDN documentation.

XDocument.Save does not give any references. It does for other methods, e.g. File.IO.Open.

like image 791
Robert Strauch Avatar asked Jun 20 '13 12:06

Robert Strauch


1 Answers

Unfortunately MSDN do not have any information about exceptions thrown by XDocument and many other types from System.Xml.Linq namespace.

But here is how saving implemented:

public void Save(string fileName, SaveOptions options)
{
    XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options);
    if ((declaration != null) && !string.IsNullOrEmpty(declaration.Encoding))
    {
        try
        {
            xmlWriterSettings.Encoding = 
               Encoding.GetEncoding(declaration.Encoding);
        }
        catch (ArgumentException)
        {
        }
    }

    using (XmlWriter writer = XmlWriter.Create(fileName, xmlWriterSettings))    
        Save(writer);        
}

If you will dig deeper, you'll see that there is large number of possible exceptions. E.g. XmlWriter.Create method can throw ArgumentNullException. Then it creates XmlWriter which involves FileStream creation. And here you can catch ArgumentException, NotSupportedException, DirectoryNotFoundException, SecurityException, PathTooLongException etc.

So, I think you should not try to catch all this stuff. Consider to wrap any exception in application specific exception, and throw it to higher levels of your application:

public void Write(XDocument outputXml, string outputFilename) 
{
   try
   {
       outputXml.Save(outputFilename);
   }
   catch(Exception e)
   {
       throw new ReportCreationException(e); // your exception type here
   } 
}

Calling code can catch only ReportCreationException and log it, notify user, etc.

like image 88
Sergey Berezovskiy Avatar answered Nov 14 '22 23:11

Sergey Berezovskiy