列表理解中的Python异常处理

2024-03-29 15:02:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

[plot_pdf(f) for f in file_list]

我想使用try except块跳过迭代循环期间可能出现的任何错误并继续下一个文件。那么在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。


Tags: 文件函数代码in列表forpdfplot
3条回答

除非在plot_pdf或包装器中处理错误,否则您将陷入for循环。

def catch_plot_pdf(f):
    try:
        return plot_pdf(f)
    except:
        print("Exception: ", sys.exc_info()[0])

[catch_plot_pdf(f) for f in file_list]

您可以创建一个catch对象

def catch(error, default, function, *args, **kwargs):
    try: return function(*args, **kwargs)
    except error: return default

那你就可以了

# using None as default value
result (catch(Exception, None, plot_pdf, f) for f in file_list)  

然后你就可以做你想做的事情了:

result = list(result)  # turn it into a list
# or
result = [n for n in result if n is not None]  # filter out the Nones

不幸的是,这甚至不是远程C速度,see my question here

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.

相关问题 更多 >