pythonpython-3.xubuntuerror-handlingtry-except

Catch a Specific OSError Exception in Python 3


In Python 3, how can we catch a specific OSError exception?

My current code catches all OSError, but only OSError: [Errno 12] needs to be caught.

try:
    foo()
except OSError as e:
    print('Caught OSError: [Errno12]')

The full error message is:

Caught OSError: [Errno12] Cannot allocate memory

How can we let Python catch only the Errno12 variant of OSError?


Solution

  • You can use the errno attribute of the OSError. For an error:

    >>> raise OSError(12, 'Some Error')
    Traceback (most recent call last):
    
      File "<ipython-input-5-8a046f16ebb6>", line 1, in <module>
        raise OSError(12, 'Some Error')
    
    OSError: [Errno 12] Some Error
    

    Use the following:

    try:
        raise OSError(12, 'Some Error')
    except OSError as e:
        if e.errno == 12:
            print('OSError no. 12 caught')
        else:
            raise
    
    # Output:
    # OSError: [Errno 12] Some Error