【问题标题】:Raising specific exceptions in Python在 Python 中引发特定异常
【发布时间】:2021-10-28 09:47:02
【问题描述】:

我有将 XML 解析为 JSON 的 Python 代码。虽然它可以正常工作,但我希望通过引发一些异常来使其更加健壮。这是我当前的代码:

    result['answer'].append({
        'multiplier': int(element.findall(r'Multiplier')[0].text), # This is an int
        'enabled': bool(element.attrib['enabled']), # This is bool
        'symbols': sym
    })

在上面的代码中,我想提出:如果我们无法将 element.attrib['enabled'] 解析为 bool,则为 XMLBooleanParsingError();如果我们无法解析第 2 行,我想提出 XMLIntegerParsingError()。

我尝试了多种方法,例如:

result['answer'].append({
    'multiplier': int(element.findall(r'Multiplier')[0].text), # This is an int
    try:
        'enabled': bool(element.attrib['enabled'])
    except:
        raise XMLBooleanParsingError()
    'symbols': sym
})

但我遇到了错误。我想在将结果存储在 JSON 中时捕获异常。有哪些方法可以遵循?

【问题讨论】:

  • Re “我遇到错误”:但不是因为评论字符的小问题?是在原始代码中吗?

标签: python python-3.x exception


【解决方案1】:

TL;DR:可能最简单的解决方案是创建 parse_intparse_bool 函数,它们会抛出 XMLBooleanParsingError。

Python 没有您尝试使用的语法,我什至不确定您是否可以在 lambdas 中编写 try/catch 块。幸运的是,您可以在任何地方定义函数,所以这应该不是问题。

def parse_int(s: str) -> int:
    try:
        return int(s)
    except ValueError as ex:
        raise XMLIntParsingError from ex # gives more verbose and comprehendible exception message

附带说明,bool(s) 很可能不是您想要解析布尔值的方式,因为 bool("false") == Truebool("0") == True

【讨论】:

    【解决方案2】:

    你不能像那样使用 try-except 。 append 命令需要在 try-except 的“try”块中,而不是在字典定义中。

    try:
        result['answer'].append({
            'multiplier': int(element.findall(r'Multiplier')[0].text), 
            'enabled': bool(element.attrib['enabled']),
            'symbols': sym
        })
    except:
        raise XMLBooleanParsingError()
    

    我觉得单独解析参数比较好,看看解析过程中是否有异常抛出,如果一切都成功了才插入字典。

    【讨论】:

      【解决方案3】:

      如果您希望每次解析都有单独的异常,这是更好的方法:

      try:
          multi = int(element.findall(r'Multiplier')[0].text)
      except exception as e:
          raise [your exception]()
      try:
          enable = bool(element.attrib['enabled'])
      except exception as e:
          raise [your exception]()
      result['answer'].append({
          'multiplier':multi  , // This is an int
          'enabled': enable , // This is bool
          'symbols': sym
      })
      

      您可以一次性完成,但您需要知道您要捕获什么异常:

      try:
          multi = int(element.findall(r'Multiplier')[0].text)
          raise [your exception]()
          enable = bool(element.attrib['enabled'])
          result['answer'].append({
          'multiplier':multi  , // This is an int
          'enabled': enable , // This is bool
          'symbols': sym
          })
      except [first exception] as e:
          raise [your exception]()
      except [second exception] as e:
          raise [your exception]()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-18
        • 1970-01-01
        • 2019-07-15
        • 1970-01-01
        • 2021-10-04
        • 1970-01-01
        • 2019-03-02
        • 1970-01-01
        相关资源
        最近更新 更多