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.
You could create a
catch
objectThen you can do
And then you can do what you want with the result:
Unfortunately this will not be even remotely C speed, see my question here
If
plot_pdf(f)
throws an error during execution of comprehension, then, it is caught in theexcept
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).
More here.
You're stuck with your
for
loop unless you handle the error insideplot_pdf
or a wrapper.