擅长:python、mysql、java
<pre><code>try:
[plot_pdf(f) for f in file_list] # using list comprehensions
except:
print ("Exception: ", sys.exc_info()[0])
continue
</code></pre>
<p>如果<code>plot_pdf(f)</code>在执行comprehension时抛出错误,那么,它被捕获在<code>except</code>子句中,则不会计算comprehension中的其他项。</p>
<p>在列表理解中不可能处理异常,因为列表理解是一个包含其他表达式的表达式,仅此而已(即没有语句,只有语句才能捕获/忽略/处理异常)。</p>
<blockquote>
<p>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).</p>
</blockquote>
<p><a href="https://stackoverflow.com/questions/1528237/how-can-i-handle-exceptions-in-a-list-comprehension-in-python">More here.</a></p>