try..except with empty exceptions

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


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:


exceptions = ( TypeError, ValueError )

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


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 found use case for it, e.g. when I want to have a method with 'exceptions' argument:


def catch_exceptions(exceptions=()):
  try:
     do_something()
  except exceptions:
     do_something_else()


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