【问题标题】:How can I handle an exception based on the RESTRING IN C#?如何根据 C# 中的 RESTRING 处理异常?
【发布时间】:2019-11-30 00:33:12
【问题描述】:

我有一个函数可以在 try 和 catch 语句中解析 XML 文件,因此每当发生错误时,我都会捕获 XmlException 类型。 问题是我想捕获异常并仅在发生某种异常时返回错误。

我尝试解析不同类型的错误格式的 XML,我注意到在抛出的 XmlException 对象中,唯一不同于不同异常的是消息、res 和 restring 属性。 但是 res 和 restring 不可访问,它们是我实际查看异常是否为 Xml_BadNameChar 错误的唯一方法。

我可以检查消息属性,但我认为这不是最优雅的方式

【问题讨论】:

  • 您认为您可以包含异常消息(以及您掌握的有关其发生原因的任何信息)以提供更多背景信息吗?我不认为这个异常有一个 InnerException 可以访问以获取更多信息?
  • 与其等待异常,您能不先寻找您不会告诉我们的“错误格式”吗?
  • 我有两篇关于异常处理的文章,我喜欢链接:blogs.msdn.microsoft.com/ericlippert/2008/09/10/… | codeproject.com/Articles/9538/… |不幸的是,您不能依赖该消息。在本地化和修复错误之间,可能出错的地方太多了。除非他们提供子类或属性来确定具体原因,否则我认为您没有可靠的选择。

标签: c# .net xml


【解决方案1】:

我不会尝试对消息执行此操作。消息是字符串。 “弦乐有耐心”。永远不要在消息中存储数据。切勿尝试从消息中检索它。如果语言环境发生变化,或者他们曾经修复或引入拼写错误,所有代码都会中断。

警告:除非您当然可以从框架中获取字符串。不过,不知道该怎么做。

XmlException 并没有很多用于区分的非字符串属性: https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmlexception?#properties

InnerException、HResult 和 Data 值得一看。

至于在您决定处理或抛出异常之前对异常进行较晚/更详细的检查,我给您我的 TryParse 代码(为仍然锁定在 1.1 中的人编写):

//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).

bool TryParse(string input, out int output){
  try{
    output = int.Parse(input);
  }
  catch (Exception ex){
    if(ex is ArgumentNullException ||
      ex is FormatException ||
      ex is OverflowException){
      //these are the exceptions I am looking for. I will do my thing.
      output = 0;
      return false;
    }
    else{
      //Not the exceptions I expect. Best to just let them go on their way.
      throw;
    }
  }

  //I am pretty sure the Exception replaces the return value in exception case. 
  //So this one will only be returned without any Exceptions, expected or unexpected
  return true;

}

在所有 3 异常情况下,处理是相同的。但是他们唯一的共同基类是不方便的——异常。 我必须赶上异常 - 比我更舒服的方式。但是我应该用 if 来消除这种过度的(所有的误报)。你可以在那里放任何你想要的逻辑。

但请注意,如果您只想在此处处理一些 Xml异常,我觉得您的处理代码可能结构不佳。

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 2013-02-18
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多