Handling exceptions with Py2 and Py3

Ben Finney ben+python at benfinney.id.au
Fri May 27 09:18:37 EDT 2016


Pavlos Parissis <pavlos.parissis at gmail.com> writes:

> So, we have ConnectionRefusedError in Python3 but not in Python2.
> Six module doesn't provide a wrapper about this.

There are many new exception types in Python 3 that inherit from
OSError. They are designed to be more precise than disambiguuating the
many reasons an OSError might be raised.

In Python 2, the same condition causes an OSError with the ‘errno’
attribute equal to ‘errno.ECONNREFUSED’.

> What is most efficient way to handle this situation in a try-catch
> block?

Others may come up with more efficient ways, depending on what you're
trying to maximise. Here is one robust way, with code that (if I've
written it right) works unchanged on Python 2 and Python 3::

    import errno

    try:
        ConnectionRefusedError
    except NameError:
        ConnectionRefusedError = NotImplemented

    try:
        short_routine()
    except ConnectionRefusedError as exc:
        handle_connection_refused(exc)
    except OSError as exc:
        if exc.errno == errno.ECONNREFUSED:
            handle_connection_refused(exc)
        else:
            raise

-- 
 \           “People are very open-minded about new things, as long as |
  `\         they're exactly like the old ones.” —Charles F. Kettering |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list