If the XmlException.SourceUri is read-only, what good is it?
I have a couple of places in my code where this is throwing a new System.Xml.XmlException. I could just do
throw new XmlException("Your XML sucks go fix it then try again.");
But I think it's best to take advantage of the exception class members whenever possible (otherwise I could throw out a simple ol every time Exception
). SourceUri and LineNumber would be helpful, but they only have methods get
, so I can't assign a value to them! There are only 3 constructor overloads, and none of them have parameters for these members; I can only initialize Message
, nothing else.
There must be some way to fill these data items with values, otherwise why does the XmlException bother them?
I suppose I can create a new class that inherits the XmlException and write a new constructor that initializes the SourceUri, etc., but still there must be a way to just use the XmlException. Right?
a source to share
There is a constructor that takes a parameter sourceUri
:
internal XmlException(string res, string[] args, string sourceUri)
But since it is internal, it can only be called inside the System.Xml assembly. Anyway, I don't think you should leave XmlException
yourself. This exception is usually thrown by XML related BCL classes. You should rather create your own exception and throw it away.
a source to share
There is a constructor with line number and line position . I don't see anything that SourceUri takes, though ...
I believe you can fill it using the streaming context, but that would be pretty fragile.
I think it is best to think of this as something that is effectively provided only through the XmlExceptions caught by the system. I don't think that makes it useless - less flexible than it could be. (I suspect that the vast majority of XmlExceptions that are thrown in the world are thrown by the system, not user code.)
a source to share
I looked using Reflector and it would appear that only two constructors set the SourceUri. This is deserialization and one internal constructor that sets everything, but all the public ones call it with SourceUri set to zero. Obviously, none of them can be readily available. I would conclude that there is no good way to set the SourceUri property.
a source to share