首页 > 解决方案 > 空元组作为python中的exception的参数

问题描述

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

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 个异常,

但是空元组的行为是什么?它只是抓住

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

我的猜测是 1,但我想不出快速测试它的方法。我的想法是,除了没有参数之后将是除了无,但一个空元组就像说“捕获此列表中的所有内容”,但列表中没有任何内容,因此没有捕获任何内容。

谢谢!

标签: pythonexception-handlingtuplesexcept

解决方案


答案是 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:

推荐阅读