【发布时间】: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块中的代码处理。