我有一个名为 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).
关于列表理解中的 Python 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16610997/