concurrent.futures 使用 try except 时不抛出异常

concurrent.futures does not throw exception when using try except

当使用 concurrent.futures.ThreadPoolExecutor() 时,它不会为 try except 抛出异常。

例如:

num = [1,2,3,4,5]
def div():
    for i in num:
        return i/0
    print('Done')

try:
    div()
except:
    print('Not Divisible by 0')

上面的代码打印了 except 部分,但下面的代码没有打印

num = [1,2,3,4,5]
def div(i):
    return i/0

try:
    with concurrent.futures.ThreadPoolExecutor() as executor:
        executor.map(div, num)
    print('Done')
except:
    print('Not Divisible by 0')

executor.map 不会立即引发异常。相反,当值为 retrieved from the iterator 时将引发异常。例如试试这个,

>>> num = [1,2,3,4,5]
>>>
>>> def div(i):
...     return i/0
...
>>> import concurrent.futures
>>>
>>> with concurrent.futures.ThreadPoolExecutor() as executor:
...     result = executor.map(div, num)
...
>>> result # Not evaluated yet
<generator object Executor.map.<locals>.result_iterator at 0x0000019E60A36570>
>>> list(result) # This will raise the `ZeroDivisionError` exception

因此,要获得预期的行为,请在 try 块中评估 executor.map 的 return 值。