Search code examples
pythonexceptiontuplesexcept

Empty tuple as argument to except in python


I'm writing a utility module and trying to make it as generic as possible, and I'm trying to work out what the behavior would be here:

for i in xrange(num_tries):
  try:
    return func(*args, **kwards)
  except exceptions as e: 
    continue

I understand that

except:

Will catch ALL exceptions, and that

except (some, tuple, of, exceptions) as e:

Will catch those 4 exceptions,

But what is the behavior of an empty tuple? Does it simply catch

  1. No exceptions
  2. All exceptions

My guess is 1, but I can't think of quick way to test it. My thinking is that except with no parameters after would be except None, but an empty tuple would just be like saying "catch everything in this list", but there's nothing in the list so nothing is caught.

Thanks!


Solution

  • The answer is 1: no exceptions, in Python 2 and in Python 3.

    exceptions = ()
    try:
        a = 1 / 0
    except exceptions as e:
        print ("the answer is 2")
    
    Traceback (most recent call last):  File "<pyshell#38>", line 2, in <module>
    a = 1 / 0
    ZeroDivisionError: integer division or modulo by zero
    

    If you want to the behaviour of answer 2 when the list of exceptions is empty, you can do

    except exceptions or (Exception,) as e: