【问题标题】:Python: How to properly handle an exception using 'ask for forgiveness' (try–except) approach?Python:如何使用“请求宽恕”(try-except)方法正确处理异常?
【发布时间】:2022-01-20 12:07:42
【问题描述】:

我的自定义异常遇到了问题,因为它们退出进程(解释器显示回溯)而不是在代码中正确处理。由于我没有太多使用自定义异常和从同一代码中的模块导入的异常正常工作的经验,我强调我在定义异常时犯了一些错误,但我找不到合适的文档来自己修复它。

这是一个示例代码。

它应该检查用户输入的 XML 路径是否有效(通过 work 我的意思是它返回该 XML 元素节点中包含的值),如果它不起作用,它会引发 XMLPrefixMissing异常(由于 XML 路径中可能缺少命名空间前缀)。然后它使用带有通配符运算符的 XML 路径代替命名空间前缀),但如果它仍然不起作用,它会引发 XMLElementNotFound(由于元素可能不在 XML 文件中)。

import xml.etree.ElementTree as ElementTree

class Error(Exception):
    """Error base class"""
    pass

class XMLPrefixMissing(Error):
    """Error for when an element is not found on an XML path"""
    def __init__(self,
    message='No element found on an XML path. Possibly missing namespace prefix.'):
        self.message = message
        super(Error, self).__init__(message)

class XMLElementNotFound(Error):
    """Error for when an element value on an XML path is an empty string"""
    def __init__(self, message='No element found on an XML path.'):
        self.message = message
        super(Error, self).__init__(message)

# Some code

file = '.\folder\example_file.xml'
xml_path = './DataArea/Order/Item/Description/ItemName'
xml_path_with_wildcard = './{*}DataArea/{*}Order/{*}Item/{*}Description/{*}ItemName'
namespaces = {'': 'http://firstnamespace.example.com/', 'foo': 'http://secondnamespace.example.com/'}

def xml_parser(file, xml_path, xml_path_with_wildcard, namespaces):
    tree = ElementTree.parse(file)
    root = tree.getroot()
    try:
        if root.find(xml_path, namespaces=namespaces) is None:
            raise XMLElementNotFound
        # Some code
    except XMLPrefixMissing:
        if root.find(xml_path_with_wildcard, namespaces=namespaces) is None:
            raise XMLElementValueEmpty
        # Some code
    except XMLElementNotFound as e:
        print(e)

【问题讨论】:

  • 有什么问题?问题是什么?从帖子中不清楚
  • 如果我没记错的话,你的问题是你所做的异常没有被提出,但 xml 模块中的异常是?如果是这样,是的,它应该是这样工作的,你应该做的是从 xml 模块导入异常并捕获它们,而不是捕获你自己的,因为你的异常不会从模块内部引发没有在任何地方定义它们。
  • @gold_cy 抱歉,我目前的问题是那些自定义异常退出整个过程,而不是由 except 块中的代码处理。

标签: python exception


【解决方案1】:

根据经验,try-except 块类似于 if/elif/else 链。

在我看来,您正试图在一个 except 块中引发异常,希望它会在下一个 except 块中被捕获。

相反,您应该尝试考虑 try 块中的所有异常,并且只使用不同的 except 块来捕获不同的异常。

try:
    if root.find(xml_path, namespaces=namespaces) is None:
        raise XMLElementNotFound
    elif root.find(xml_path_with_wildcard, namespaces=namespaces) is None:
        raise XMLElementValueEmpty
except XMLPrefixMissing:
    #some code
except XMLElementValueEmpty as e:
    print(e)

【讨论】:

  • 这非常有帮助,让我以更好的方式重新排列我的代码。非常感谢!
猜你喜欢
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-03
  • 2016-09-23
  • 2021-07-20
  • 1970-01-01
相关资源
最近更新 更多