列表理解中的 Python 异常处理

标签 python exception-handling list-comprehension

我有一个名为 plot_pdf(f) 的 Python 函数,它可能会引发错误。我使用列表理解来迭代此函数的文件列表:

[plot_pdf(f) for f in file_list]

我想使用 try-except block 在迭代循环中跳过任何可能的错误并继续处理下一个文件。那么下面的代码是不是在 Python 列表理解中进行异常处理的正确方法?

try:
    [plot_pdf(f) for f in file_list]  # using list comprehensions
except:
    print ("Exception: ", sys.exc_info()[0])
    continue

上面的代码会不会终止本次迭代,进入下一次迭代?如果我不能使用列表推导来捕获迭代期间的错误,那么我必须使用普通的 for 循环:

for f in file_list:
    try:
        plot_pdf(f)
    except:
        print("Exception: ", sys.exc_info()[0])
        continue

我想知道我是否可以使用 try-except 在列表理解中进行异常处理。

最佳答案

try:
    [plot_pdf(f) for f in file_list]  # using list comprehensions
except:
    print ("Exception: ", sys.exc_info()[0])
    continue

如果plot_pdf(f)在comprehension执行过程中抛出错误,那么,它被捕获在except子句中,comprehension中的其他项将不会被评估。

不可能在列表推导中处理异常,因为列表推导是一个包含其他表达式的表达式,仅此而已(即没有语句,只有语句可以捕获/忽略/处理异常)。

Function calls are expression, and the function bodies can include all the statements you want, so delegating the evaluation of the exception-prone sub-expression to a function, as you've noticed, is one feasible workaround (others, when feasible, are checks on values that might provoke exceptions, as also suggested in other answers).

More here.

关于列表理解中的 Python 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16610997/

相关文章:

python - 如何在 Flask 中进行首次迁移?

python - python 3中的SQLAlchemy ER图

c# - await Task.WhenAll(tasks) 异常处理,记录来自任务的所有异常

python - 如何在 django-filter 中包含列表理解结果?

Python 列表理解 : Modify list elements if a certain value occurs

python - 打印报表在时限后消失

python - 将对角线渐变倾斜为垂直

asp.net-web-api - 如何在Web API 2应用程序中全局捕获和记录所有异常/错误?

powershell - 测试路径返回权限被拒绝 - 如何进行错误处理

python - Python 2d 列表理解中的按引用传递问题