Search code examples
pythonexceptionconcurrent.futurestry-except

concurrent.futures does not throw exception when using try except


When using concurrent.futures.ThreadPoolExecutor() it doesn't throw an exception for try except.

For eg:

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')

The above code prints the except part but the below code doesn't

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')

Solution

  • executor.map does not raise the exception right away. Instead that exception will be raised when the value is retrieved from the iterator. For example try this,

    >>> 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
    

    So to get the expected behavior, evaluate the return value of executor.map within the try block.