MSDN Documentation

XmlException Class

Namespace: System.Xml

Represents an error that occurs when processing XML, and provides exception data.

Syntax

public class XmlException : System.SystemException

Inheritance Hierarchy

Hierarchy
System.Object
System.Exception
System.SystemException
System.Xml.XmlException

Constructors

The XmlException class has the following constructors:

Constructor Description
XmlException()
XmlException(string message)
XmlException(string message, System.Exception innerException)
Initializes a new instance of the XmlException class with a default error message, or a specified error message and inner exception.

Remarks

When an error occurs during XML processing, the XmlException is thrown. This exception can be caught and handled to provide more specific error information to the user or for logging purposes.

The XmlException provides properties such as:

Example

The following example demonstrates how to catch an XmlException when parsing an invalid XML string.


using System;
using System.Xml;

public class Example
{
    public static void Main(string[] args)
    {
        string invalidXml = "<root><element>This is not well-formed XML</root>";

        try
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(invalidXml);
        }
        catch (XmlException ex)
        {
            Console.WriteLine("An XML error occurred:");
            Console.WriteLine($"  Message: {ex.Message}");
            Console.WriteLine($"  Line Number: {ex.LineNumber}");
            Console.WriteLine($"  Line Position: {ex.LinePosition}");
            if (ex.SourceUri != null)
            {
                Console.WriteLine($"  Source URI: {ex.SourceUri}");
            }
        }
        catch (Exception ex) // Catch other potential exceptions
        {
            Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        }
    }
}
            

See Also