空元组作为 python 中 except 的参数

Empty tuple as argument to except in python

我正在编写一个实用程序模块并尝试使其尽可能通用,并且我正在尝试找出此处的行为:

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

我明白

except:

将捕获所有异常,并且

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

将捕获这 4 个异常,

但是空元组的行为是什么?是不是简单的catch

  1. 没有例外
  2. 所有例外

我猜是 1,但我想不出快速测试它的方法。我的想法是,除了 None 之外没有参数,但是空元组就像说 "catch everything in this list",但是列表中没有任何内容,所以什么也没有被捕获。

谢谢!

答案是 1:没有例外,在 Python 2 和 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

如果你想在异常列表为空时执行答案 2 的行为,你可以这样做

except exceptions or (Exception,) as e: