try..except with empty exceptions

Chris Angelico rosuav at gmail.com
Fri Apr 10 04:58:23 EDT 2015


On Fri, Apr 10, 2015 at 6:48 PM, Pavel S <pavel at schon.cz> wrote:
> Hi,
>
> I noticed interesting behaviour. Since I don't have python3 installation here, I tested that on Python 2.7.
>
> Well known feature is that try..except block can catch multiple exceptions listed in a tuple:
>
> However when exceptions=(), then try..except block behaves as no try..except block.
>
> exceptions = ()
>
> try:
>     a, b = None   # <--- the error will not be catched
> except exceptions, e:
>     print 'Catched error:', e
>
> I believe that behaviour is not documented. What you think?

It's no different from any other except clause that doesn't match. An
empty tuple of exception types can never match any actual exception
thrown, so it'll be like skipping that except block. It doesn't need
to be specifically documented, as it's a natural consequence of the
use of the empty tuple there.

However, even though it's perfectly plausible as regards language
definition, I would hesitate to use it in production code. I'm not
sure this makes your code any better.

Side point: Even though you're not using Python 3 (where it's
mandatory), I would recommend using the "as" syntax with except
clauses:

exceptions = ()
try:
    a, b = None
except exceptions as e:
    print("Can't happen")

Writing your code to be compatible with both 2.7 and 3.x will make the
eventual port easier.

ChrisA



More information about the Python-list mailing list