【问题标题】:concurrent.futures does not throw exception when using try exceptconcurrent.futures 在使用 try except 时不会抛出异常
【发布时间】:2023-03-05 16:36:01
【问题描述】:

当使用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')

【问题讨论】:

  • 从执行器获取结果,然后会看到异常。像这样try: with concurrent.futures.ThreadPoolExecutor() as executor: results=executor.map(div, num) for result in results: print(result) print('Done')

标签: python exception concurrent.futures try-except


【解决方案1】:

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 的返回值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 2017-04-03
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多