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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With