python - 空元组作为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,但我想不出快速测试它的方法。我的想法是,除了没有参数之后将是除了无,但一个空元组就像说“捕获此列表中的所有内容”,但列表中没有任何内容,因此没有捕获任何内容。
谢谢!
解决方案
答案是 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:
推荐阅读
- python - 读取发送到 AWS Lambda 的 CSV 格式的时间序列数据
- python - 发生异常,使用 %tb 查看完整的回溯。(argparse 错误)
- google-cloud-platform - 无法在工作区中创建数据块集群
- python - 将图像与内核卷积会返回空图像
- postgresql - 使用数组取消嵌套批量插入两个表
- python - 不正确的代码执行(额外文本) Discord.py
- kubernetes - 在 Ansible 中修补多文档 YAML 文件的最简洁方法
- javascript - 快速到数据库的异步调用 *SOMETIMES* 失败
- r - 如何从表中删除所有 NA 并创建一个更小的压缩表?
- php - 将标题添加到 PHP 电子邮件