try..except with empty exceptions

Pavel S pavel at
Fri Apr 10 10:48:06 CEST 2015


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:

exceptions = ( TypeError, ValueError )

    a, b = None
except exceptions, e:
    print 'Catched error:', e

However when exceptions=(), then try..except block behaves as no try..except block.

exceptions = ()

    a, b = None   # <--- the error will not be catched
except exceptions, e:
    print 'Catched error:', e

I found use case for it, e.g. when I want to have a method with 'exceptions' argument:

def catch_exceptions(exceptions=()):
  except exceptions:

catch_exceptions()               # catches nothing
catch_exceptions((TypeError,))   # catches TypeError

I believe that behaviour is not documented. What you think?

More information about the Python-list mailing list