python 中的错误处理和保存错误

Error handling and saving error in python

我有一个 for 循环,它迭代一个列并进行一些 xml 处理。我遇到了一些错误,但我不想只是传递它们,而是想将它们作为输出的一部分保存到一个单独的列表中。这是我目前所拥有的:

def outputfunc(column_name):
    output = []
    errors = []
    for i in column_name:
        try:
            tree = etree.fromstring(i)
        except:
            errors.append(i) #basic logic here is that i append errors with i that raise error and then pass
            pass

详述 Carcigenicates 评论,如果您想使用 Exception 基数 class 查找所有错误,您可以将代码更改为:

def outputfunc(column_name):
    output = []
    errors = []
    for i in column_name:
        try:
            tree = etree.fromstring(i)
        except Exception as e:
            errors.append(e) #basic logic here is that i append errors with i that raise error and then pass

这会将 e 设置为错误消息的文本。 e 然后附加到错误。此外,我删除了一个非功能性的 pass 语句。但是,你目前没有办法输出错误,所以我建议使用

print('\n'.join(map(str,errors)))

在outputfunc的范围内。此外,正如 Paul Cornelius 所建议的那样,以元组格式返回您的输出和错误会很有用。这将使您的代码

def outputfunc(column_name):
    output = []
    errors = []
    for i in column_name:
        try:
            tree = etree.fromstring(i)
        except Exception as e:
            errors.append(e) #basic logic here is that i append errors with i that raise error and then pass
    print('\n'.join(map(str,errors)))
    return output, errors

参考资料

2. Lexical analysis — Python 3.9.6 documentation

Built-in Exceptions — Python 3.9.6 documentation