【问题标题】:Can't catch System.Xaml.XamlParseException无法捕获 System.Xaml.XamlParseException
【发布时间】:2012-08-08 19:07:28
【问题描述】:

我有一个空字符串,当我在 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();
}

【问题讨论】:

  • try,catch 没有响应”是什么意思?我刚刚运行了您的确切代码,它很好地捕获了异常。 (当然,您最好抓住您期望的特定异常。)
  • 我想我得清理一下我的项目,我会试试看
  • 还是不行,有没有办法检测根元素是否存在,@RV1987

标签: c# wpf xaml exception-handling xml-parsing


【解决方案1】:
object ob = System.Windows.Markup.XamlReader.Load(xmlReader);

您在这里使用的是 Windows 标记 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-09
    • 2011-03-14
    • 2012-03-15
    • 2014-11-25
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多