Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #109170
| From | Ben Finney <ben+python@benfinney.id.au> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Handling exceptions with Py2 and Py3 |
| Date | 2016-05-27 23:18 +1000 |
| Message-ID | <mailman.19.1464355141.2277.python-list@python.org> (permalink) |
| References | <57483C86.6030304@gmail.com> <8537p3abbm.fsf@benfinney.id.au> |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Handling exceptions with Py2 and Py3 Ben Finney <ben+python@benfinney.id.au> - 2016-05-27 23:18 +1000
csiph-web