C# Can';t catch System.Xaml.XamlParseException

C# Can';t catch System.Xaml.XamlParseException,c#,wpf,xaml,exception-handling,xml-parsing,C#,Wpf,Xaml,Exception Handling,Xml Parsing,我有一个空字符串,当我在XmlReader上使用它时,它当然会给出一个解析“根元素丢失”异常,我试图捕获它,但try,catch没有响应,是否有方法捕获此异常或检测我的字符串不可解析 System.IO.StringReader stringReader = new System.IO.StringReader(""); System.Xml.XmlReader xmlReader = System.Xml.XmlTextReader.Create(stringReader, new Syst

我有一个空字符串,当我在XmlReader上使用它时,它当然会给出一个解析“根元素丢失”异常,我试图捕获它,但
try,catch
没有响应,是否有方法捕获此异常或检测我的字符串不可解析

System.IO.StringReader stringReader = new System.IO.StringReader("");

System.Xml.XmlReader xmlReader = System.Xml.XmlTextReader.Create(stringReader, new System.Xml.XmlReaderSettings());

try
{
    object ob = System.Windows.Markup.XamlReader.Load(xmlReader);//
    mycv = (Canvas)ob;
}
    catch (Exception ex) //even if I use System.Xaml.XamlParseException
{
    mycv = new Canvas();
}
这里您使用的是Windows markup XamlReader,因此不会在这里抛出
System.Xaml.XamlParseException
,您应该捕获
System.Windows.markup.XamlParseException

这应该对你有用-

try
{
    object ob = System.Windows.Markup.XamlReader.Load(xmlReader);//
    mycv = (Canvas)ob;
}
    catch (System.Windows.Markup.XamlParseException ex)
{
    mycv = new Canvas();
}

你所说的“试一试”是什么意思?我刚刚运行了你的代码,它很好地捕捉到了异常。(当然,你最好抓住你期望的特殊情况。)我想我必须清理我的项目,我会给它一个幽会不起作用,有没有办法检测根元素是否存在,@RV1987
try
{
    object ob = System.Windows.Markup.XamlReader.Load(xmlReader);//
    mycv = (Canvas)ob;
}
    catch (System.Windows.Markup.XamlParseException ex)
{
    mycv = new Canvas();
}