且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

列表理解中的Python异常处理

更新时间:2023-02-18 12:08:15

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

如果 plot_pdf(f)在执行理解期间抛出错误, ,它被捕获在,除了子句,理解的其他项目将不被评估。



它不是可能在列表解析中处理异常,因为列表的理解是一个包含其他表达式的表达式表达,没有更多(即函数调用是表达式,函数体可以包括所有的b $ b你想要的语句,所以将
异常容易的子表达式的评估委托给一个函数,如你所注意到的那样,是
一个可行的解决方法(其他的,在可行时,是检查

更多在这里


I have a Python function called plot_pdf(f) that might throw an error. I use a list comprehension to iterate over a list of files on this function:

[plot_pdf(f) for f in file_list]

I want to use try-except block to skip any possible errors during the iteration loop and continue with the next file. So is the following code correct way to do the exception handling in Python list comprehension?

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

Will the above code terminate the current iteration and go to the next iteration? If I can't use list comprehension to catch errors during iteration, then I have to use the normal for loop:

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

I want to know if I can use try-except to do exception handling in list comprehension.

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

If plot_pdf(f) throws an error during execution of comprehension, then, it is caught in the except clause, other items in comprehension won't be evaluated.

It is not possible to handle exceptions in a list comprehension, for a list comprehension is an expression containing other expression, nothing more (i.e. no statements, and only statements can catch/ignore/handle exceptions).

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.