Handling exceptions with Py2 and Py3
Steven D'Aprano
steve at pearwood.info
Fri May 27 08:51:37 EDT 2016
On Fri, 27 May 2016 10:24 pm, Pavlos Parissis wrote:
> Hi,
>
> So, we have ConnectionRefusedError in Python3 but not in Python2.
> Six module doesn't provide a wrapper about this.
>
> What is most efficient way to handle this situation in a try-catch block?
Um, could you give us a hint as to context?
What does Python 2 raise instead of ConnectionRefusedError? I don't know, so
for the sake of calling it *something* I'll say it's FooError. Then if it
is a simple name, you can do this:
if sys.version < "3":
ConnectionRefusedError = FooError
# much later
try:
do_the_thing()
except ConnectionRefusedError:
...
Or instead of checking for the version, you can check for the name:
try:
from some_module import ConnectionRefusedError
except ImportError:
# Must be Python 2
from another_module import FooError as ConnectionRefusedError
If neither of these techniques help, please give more context and we can be
more specific.
--
Steven
More information about the Python-list
mailing list