Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #109170 > unrolled thread

Re: Handling exceptions with Py2 and Py3

Started byBen Finney <ben+python@benfinney.id.au>
First post2016-05-27 23:18 +1000
Last post2016-05-27 23:18 +1000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Handling exceptions with Py2 and Py3 Ben Finney <ben+python@benfinney.id.au> - 2016-05-27 23:18 +1000

#109170 — Re: Handling exceptions with Py2 and Py3

FromBen Finney <ben+python@benfinney.id.au>
Date2016-05-27 23:18 +1000
SubjectRe: Handling exceptions with Py2 and Py3
Message-ID<mailman.19.1464355141.2277.python-list@python.org>
Pavlos Parissis <pavlos.parissis@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web