Catch a Specific OSError Exception in Python 3

Viewed 3338

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?

2 Answers

Some error numbers can differ between platforms (see e.g. this comparison). Therefore, I would recommend using the errno module in order to catch the specific type of OSError in a cross-platform way:

try:
    # Code that might fail...
except OSError as e:
    if e.errno == errno.ENOMEM:
        # Handle ENOMEM case...
    else:
        raise

You can use the dictionary errno.errocode to find the name of a specific error code in the errno module:

>>> errno.errorcode[12]
'ENOMEM'

Note that error number 12 specifically seems to be the same across most platforms, but many others differ.

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
Related